gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:58:19 25 4
gpt4 key购买 nike

在 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
^
}

关于c++ - #if 条件区域可以跨越包含文件边界吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35689094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com