是否可以将预处理器有条件地放在C宏中? [英] Is it possible to put a preprocessor conditional inside a C macro?
问题描述
有没有一种方法可以编写一个C预处理器宏,该宏根据接收到的参数而扩展为不同的东西?
Is there a way to write a C preprocessor macro that expands to different things depending on what argument it receives?
#define foo() ???
/* 1 */
foo(name)
/* 2 */
foo(_)
所需结果:
/* 1 */
int name;
/* 2 */
/*ignore*/
是的,我知道宏是邪恶的.我问这个问题主要是出于好奇.
Yes, I know macros are evil. I'm asking this mostly out of curiosity.
推荐答案
也许尝试一些多阶段宏扩展?这是提升预处理器/控件所使用的策略/if库.
Perhaps try some multi-stage macro expansion? This is the strategy used by the Boost preprocessor/control/if library.
#define FOO_NAME 1
#define FOO__ 2
#define CONC(a,b) a##_##b
#define FOO(x) CONC(FOO,x)
我认为没有任何方法可以检查C宏扩展中的条件.
I don't think there is any way to check conditions within a C macro expansion.
我想出的最好的办法是使用#
字符串化运算符将宏参数隐式转换为字符串文字,然后使用运行时函数进行检查. (不过,在您要输出变量声明的情况下,这不适用于您的情况.)
The best thing I could come up with is to covert the macro arguments to a string literal using the #
stringizing operator, and then checking using run-time functions. (This won't work for your case, though, where you want to output variable declarations.)
例如,以下显示"011":
For example, the following prints "011":
#define FOO(x) (strcmp("NAME", #x) ? 1 : 0)
main()
{
printf("%d", FOO(NAME));
printf("%d", FOO(1));
printf("%d", FOO(2));
}
编译器可能会在编译时优化strcmp
比较,因此它不会比使用真正的预处理器有条件的情况低效率.但是,将FOO
设置为普通函数会更清晰,也可能同样有效.
The compiler would likely optimize the strcmp
comparisons at compile-time so it would be no more inefficient than it would have been had genuine pre-processor conditionals been available. However, making FOO
a normal function would be clearer and probably just as efficient.
这篇关于是否可以将预处理器有条件地放在C宏中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!