C++ ifdef 中的布尔值:“#ifdef A && B”是否与“#if defined(A) && defined(B)”相同?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1312132/
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-08-27 19:31:45  来源:igfitidea点击:

Boolean in ifdef: is "#ifdef A && B" the same as "#if defined(A) && defined(B)"?

c++c-preprocessorconditional-compilation

提问by criddell

In C++, is this:

在 C++ 中,是这样的:

#ifdef A && B

the same as:

等同于:

#if defined(A) && defined(B)

?

?

I was thinking it wasn't, but I haven't been able to find a difference with my compiler (VS2005).

我认为它不是,但我无法找到与我的编译器(VS2005)的区别。

回答by Evan Teran

They are not the same. The first one doesn't work (I tested in gcc 4.4.1). Error message was:

她们不一样。第一个不起作用(我在 gcc 4.4.1 中测试过)。错误消息是:

test.cc:1:15: warning: extra tokens at end of #ifdef directive

test.cc:1:15: 警告:#ifdef 指令末尾的额外标记

If you want to check if multiple things are defined, use the second one.

如果要检查是否定义了多个事物,请使用第二个。

回答by Svetlozar Angelov

Conditional Compilation

条件编译

You can use the defined operator in the #if directive to use expressions that evaluate to 0 or 1 within a preprocessor line. This saves you from using nested preprocessing directives. The parentheses around the identifier are optional. For example:

#if defined (MAX) && ! defined (MIN)  

Without using the defined operator, you would have to include the following two directives to perform the above example:

#ifdef max 
#ifndef min

您可以在 #if 指令中使用已定义的运算符来使用预处理器行中计算结果为 0 或 1 的表达式。这使您无需使用嵌套的预处理指令。标识符周围的括号是可选的。例如:

#if defined (MAX) && ! defined (MIN)  

如果不使用定义的运算符,则必须包含以下两个指令才能执行上述示例:

#ifdef max 
#ifndef min

回答by way good

The following results are the same:

以下结果相同:

1.

1.

#define A
#define B
#if(defined A && defined B)
printf("define test");
#endif

2.

2.

#ifdef A
#ifdef B
printf("define test");
#endif
#endif

回答by MikeB

For those that might be looking for example (UNIX/g++) that is a little different from the OP, this may help:

对于那些可能正在寻找与 OP 略有不同的示例 (UNIX/g++) 的人来说,这可能会有所帮助:

`

`

#if(defined A && defined B && defined C)
    const string foo = "xyz";
#else
#if(defined A && defined B)
    const string foo = "xy";
#else
#if(defined A && defined C)
    const string foo = "xz";
#else
#ifdef A
    const string foo = "x";
#endif
#endif
#endif
#endif

回答by Fabri

As of VS2015 none of the above works. The correct directive is:

从 VS2015 开始,以上都不起作用。正确的指令是:

#if (MAX && !MIN)

see more here

在这里查看更多