C语言 如何在 C 预处理器中的 #define 中使用 #if?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2831934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:26:22  来源:igfitidea点击:

How to use #if inside #define in the C preprocessor?

cc-preprocessor

提问by Wxy

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.

我想编写一个宏,根据其参数的布尔值输出代码。所以 sayDEF_CONST(true)应该扩展为const,并且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

回答by vladr

You can simulate conditionals using macro token concatenationas 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*/

回答by GrahamS

Doing it as a paramterised macro is a bit odd.

把它作为一个参数化的宏来做有点奇怪。

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_CONSTdefined (e.g. typically something -DUSE_CONSTin the makefile or compiler options) then it will use the consts, otherwise it won't.

并且如果您使用已USE_CONST定义的(例如通常-DUSE_CONST在makefile 或编译器选项中的某些内容)进行编译,那么它将使用const,否则不会。

Edit:Actually I see Vlad covered that option at the end of his answer, so +1 for him :)

编辑:实际上我看到弗拉德在他的回答结束时提到了那个选项,所以为他 +1 :)