[英]How to use #if inside #define in the C preprocessor?
I want to write a macro that spits out code based on the boolean value of its parameter. 我想编写一个宏,根据其参数的布尔值吐出代码。 So say
DEF_CONST(true)
should be expanded into const
, and DEF_CONST(false)
should be expanded into nothing. 所以说
DEF_CONST(true)
应该扩展为const
,而DEF_CONST(false)
应该扩展为DEF_CONST(false)
。
Clearly the following doesn't work because we can't use another preprocessor inside #defines: 显然,以下方法不起作用,因为我们不能在#defines中使用另一个预处理器:
#define DEF_CONST(b_const) \
#if (b_const) \
const \
#endif
You can simulate conditionals using macro token concatenation as follows: 您可以使用宏标记连接来模拟条件,如下所示:
#define DEF_CONST(b_const) DEF_CONST_##b_const
#define DEF_CONST_true const
#define DEF_CONST_false
Then, 然后,
/* OK */
DEF_CONST(true) int x; /* expands to const int x */
DEF_CONST(false) int y; /* expands to int y */
/* NOT OK */
bool bSomeBool = true; // technically not C :)
DEF_CONST(bSomeBool) int z; /* error: preprocessor does not know the value
of bSomeBool */
Also, allowing for passing macro parameters to DEF_CONST itself (as correctly pointed out by GMan and others): 另外,允许将宏参数传递给DEF_CONST本身(正如GMan和其他人正确指出的那样):
#define DEF_CONST2(b_const) DEF_CONST_##b_const
#define DEF_CONST(b_const) DEF_CONST2(b_const)
#define DEF_CONST_true const
#define DEF_CONST_false
#define b true
#define c false
/* OK */
DEF_CONST(b) int x; /* expands to const int x */
DEF_CONST(c) int y; /* expands to int y */
DEF_CONST(true) int z; /* expands to const int z */
You may also consider the much simpler (though potentially less flexible): 您可能还会考虑更简单(尽管可能不太灵活):
#if b_const
# define DEF_CONST const
#else /*b_const*/
# define DEF_CONST
#endif /*b_const*/
Doing it as a paramterised macro is a bit odd. 把它作为一个paramterised宏有点奇怪。
Why not just do something like this: 为什么不做这样的事情:
#ifdef USE_CONST
#define MYCONST const
#else
#define MYCONST
#endif
Then you can write code like this: 然后你可以写这样的代码:
MYCONST int x = 1;
MYCONST char* foo = "bar";
and if you compile with USE_CONST
defined (eg typically something -DUSE_CONST
in the makefile or compiler options) then it will use the consts, otherwise it won't. 如果您使用定义的
USE_CONST
编译(例如,通常在makefile或编译器选项中使用-DUSE_CONST
),那么它将使用consts,否则不会。
Edit: Actually I see Vlad covered that option at the end of his answer, so +1 for him :) 编辑:其实我看到弗拉德在他的答案结束时覆盖了那个选项,所以给他+1 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.