【问题标题】:Can #if conditional areas cross include file boundaries?#if 条件区域可以跨包含文件边界吗?
【发布时间】:2016-06-11 20:59:47
【问题描述】:

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

所有条件编译指令,例如 #if 和 #ifdef,必须 在文件结束之前与关闭 #endif 指令匹配; 否则,会生成错误消息。条件编译时 指令包含在包含文件中,它们必须满足相同的 条件:必须没有不匹配的条件编译 包含文件末尾的指令。

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

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

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

【问题讨论】:

  • 您显然是在询问 C++ 标准,所以不要添加 C 标签。
  • 您是否尝试过执行此操作时会发生什么?
  • 嗯,这也与 C 有关。它有不同的标准,可能会有所不同。
  • @Alex: VisualStudio 给fatal error C1004:
  • 我可以快速浏览的唯一指示是,在标准中描述预处理指令的语法中最顶层的非终结符被命名为 preprocessing-file [cpp]。所以似乎意图是构造可能不跨越多个文件。

标签: c++ c-preprocessor language-lawyer


【解决方案1】:
#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
 ^
}

【讨论】:

  • 你定义了 FOO 吗?否则它不会包含您的标题
  • @Anedar:没关系,(但如果定义了FOO,它确实会给#else#endif 带来一些其他错误)
  • 最好将这些错误添加到您的答案中。
  • @KirillKobelev:添加了运行 cpp 的完整日志 - 因为它在编译阶段早期出错,所以“正确”编译器的输出几乎相同,只是它没有列出源内容。
  • 是的,我明白了。这些错误清楚地表明编译器对正在发生的事情的看法。
猜你喜欢
  • 2013-09-03
  • 2019-09-26
  • 2013-05-03
  • 2019-05-11
  • 2019-11-21
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多