将#elif与#ifdef一起使用是否合法?

Vio*_*ffe 4 c++ preprocessor c-preprocessor preprocessor-directive

一个简单的问题,谷歌没有帮助我.在C++中使用#elif上下文中的子句是否合法#ifdef?它似乎与c ++ 11模式(MSVC 2015/2017,clang,GCC)中的所有主要编译器一样编译和工作,但我不确定它是否符合标准.

Mic*_*rth 20

对我来说,这个问题最重要的一点其实是rosshjb在该问题下的评论:

\n
\n

@RemyLebeau 是的,我们可以将 #ifdef 与 #elif 一起使用。但是,如果我们在 #ifdef 情况下 #define 值为 0 的宏,则 #ifdef 情况会测试它是否为 true。否则,如果我们为 #elif 情况 #define 值为 0 的宏,则 #elif 情况会测试它为 false。\xe2\x80\x93\nrosshjb 2020 年 1 月 19 日 19:40

\n
\n

所以如果你有一个像这样的块:

\n
#ifdef __linux__\n  <some Linux code here>\n#elif _WIN32\n  <some Windows code here>\n#endif\n
Run Code Online (Sandbox Code Playgroud)\n

然后第二个测试与第一个显着不同 - 第一个是检查是否__linux__已定义,第二个是检查符号_WIN32计算结果是否为 true。在许多情况下,它的行为是相同的,但不能保证这样做。

\n

完整的等效实际上是:

\n
#ifdef __linux__\n  <some Linux code here>\n#elif defined(_WIN32)\n  <some Windows code here>\n#endif\n
Run Code Online (Sandbox Code Playgroud)\n

这对每个人来说可能并不明显。

\n

使用Kerrick SB的答案,你也可以写同样的#if语句:

\n
#if defined(__linux__)\n  <some Linux code here>\n#elif defined(_WIN32)\n  <some Windows code here>\n#endif\n
Run Code Online (Sandbox Code Playgroud)\n

这使得更明显的是,这defined对于两个#if和 the#elif

\n


Ker*_* SB 6

是的,语法允许#elif后面的,匹配的#if,#ifdef或者#ifndef:

if-section:
    if-group elif-groups opt else-group opt endif-line

if-group:
    # if constant-expression new-line group opt
    # ifdef identifier new-line group opt
    # ifndef identifier new-line group opt

请注意,#ifdef(X)只是简称#if defined(X),并#ifndef(X)#if ! defined(X).


Jer*_*fin 6

是的,这是允许的.

语法是:

if-group elif-groups opt else-group opt endif-line

if-group不仅包括#if而且包括#ifdef和的定义#ifndef,所以#ifdef ... #elif ... #endif很好.