gpt4 book ai didi

包含文件中的#endif 是否可以用于关闭包含文件中的#if?

转载 作者:太空狗 更新时间:2023-10-29 16:40:36 25 4
gpt4 key购买 nike

假设我有两个文件,a.h:

#if 1
#include "b.h"

b.h:

#endif

gcc 和 clang 的预处理器都拒绝 a.h:

$ cpp -ansi -pedantic a.h >/dev/null
In file included from a.h:2:0:
b.h:1:2: error: #endif without #if
#endif
^
a.h:1:0: error: unterminated #if
#if 1
^

但是,C 标准 (N1570 6.10.2.3) 说:

A preprocessing directive of the form

# include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.

这似乎允许上述构造。

gcc 和 clang 是否不符合拒绝我的代码的要求?

最佳答案

C 标准定义了 8 个翻译阶段。源文件由 8 个阶段中的每一个按顺序(或以等效方式)处理。

第 4 阶段,定义见 N1570第 5.1.1.2 节是:

Preprocessing directives are executed, macro invocations are expanded, and _Pragma unary operator expressions are executed. If a character sequence that matches the syntax of a universal character name is produced by token concatenation (6.10.3.3), the behavior is undefined. A #include preprocessing directive causes the named header or source file to be processed from phase 1 through phase 4, recursively. All preprocessing directives are then deleted.

这里的相关句子是:

A #include preprocessing directive causes the named header or source file to be processed from phase 1 through phase 4, recursively.

这意味着每个包含的源文件都是自己预处理的。这排除了 #if在一个文件和相应的 #endif 中在另一个。

(正如评论中提到的“一头野象”,以及 rodrigo's answer 所说,第 6.10 节中的语法还说明了一个以 #if(或#ifdef#ifndef ) 行并以 #endif 行结尾,只能作为预处理文件的一部分出现。)

关于包含文件中的#endif 是否可以用于关闭包含文件中的#if?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32847499/

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