#if 条件区域可以跨越包含文件边界吗?

Can #if conditional areas cross include file boundaries?

在 MSDN (https://msdn.microsoft.com/en-us/library/ew2hz0yd.aspx) 中,我看到以下内容:

All conditional-compilation directives, such as #if and #ifdef, must be matched with closing #endif directives prior to the end of file; otherwise, an error message is generated. When conditional-compilation directives are contained in include files, they must satisfy the same conditions: There must be no unmatched conditional-compilation directives at the end of the include file.

嗯,简单明了。同时我在 C++11 标准中找不到类似的东西。我的问题是这个法律限制?

我完全理解将条件编译拆分为多个 #include 层不是一个好主意,应该避免。

有人知道其他编译器(GCC、CLANG)是如何处理这种情况的吗?也许有人在某个地方讨论过这个问题?

#if FOO
#include "hashif.h"


extern "C" int printf(const char* fmt, ...);

int main()
{
    printf("Hello, World\n");
}

hashif.h 包含这个:

#define BAR 1
#else
#define BAR 2
#endif

然后clang++报错

hashif.cpp:1:2: error: unterminated conditional directive
#if FOO  
^
1 error generated.

编辑:g++cpp 的行为方式相同。

确切输出来自:

$ cpp hashif.cpp -DFOO=1
# 1 "hashif.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "hashif.cpp"

# 1 "hashif.h" 1
In file included from hashif.cpp:2:0:
hashif.h:2:2: error: #else without #if
 #else
  ^
hashif.h:3:0: warning: "BAR" redefined
 #define BAR 2
 ^
hashif.h:1:0: note: this is the location of the previous definition
 #define BAR 1
 ^
hashif.h:4:2: error: #endif without #if
 #endif
  ^
# 3 "hashif.cpp" 2


extern "C" int printf(const char* fmt, ...);

int main()
{
    printf("Hello, World\n");
hashif.cpp:1:0: error: unterminated #if
 #if FOO
 ^
}