有条件的预处理程序分布在#include文件中

use*_*697 5 c language-lawyer c-preprocessor

这合法吗?

foo.h

    #if 1
    #include "bar.h"
Run Code Online (Sandbox Code Playgroud)

bar.h

    #endif
Run Code Online (Sandbox Code Playgroud)

foo.c

    #include "foo.h"
Run Code Online (Sandbox Code Playgroud)

clang-700.1.81 以一种有趣的方式抱怨:

    In file included from foo.c:1:
    In file included from ./foo.h:2:
    ./bar.h:1:2: error: #endif without #if
    #endif
Run Code Online (Sandbox Code Playgroud)

(这意味着确实如此 #include "bar.h"

    # 3 "./foo.h" 2
    In file included from foo.c:1:
    ./foo.h:1:2: error: unterminated conditional directive
    #ifndef FOO
Run Code Online (Sandbox Code Playgroud)

(这意味着没有 #include "bar.h")。

我感到不安的是,预处理器所关心的不仅仅是标准所要求的。如果我错了,请纠正我,否则,请证明我是对的。

ric*_*ici 5

这是不合法的。尽管条件组可能包含#include指令或嵌套的条件部分,但组成条件部分的所有条件指令必须位于同一文件中。

预处理文件的语法对此约束进行了明确说明(第6.10节)。

      preprocessing-file:
               group opt
      group:
               group-part
               group group-part
      group-part:
               if-section
               control-line
               text-line
               # non-directive
      if-section:
               if-group elif-groups opt else-group opt endif-line
Run Code Online (Sandbox Code Playgroud)

§5.1.1.2第4段也隐含了该约束,该段将#include指令的功能描述为阶段1至4的递归执行,而不是简单的文本包含:

#include预处理指令使命名的头文件或源文件从阶段1到阶段4进行递归处理。