在 ifdef 中的布尔值: “ # ifdef A & & B”是否与“ # 如果定义(A) & & 定义(B)”相同?

在 C + + 中,是这样的:

#ifdef A && B

与:

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

我认为它不是,但我还没有能够找到与我的编译器(VS2005)的差异。

106944 次浏览

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

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

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

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

The following results are the same:

1.

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

2.

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

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

#if (MAX && !MIN)

see more here

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

`

#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