预处理指令之前的空宏的标准行为

Standard Behavior Of An Empty Macro Preceding A Preprocessing Directive

举个例子:

#define FOO
FOO #define BAR 1
BAR

根据 ANSI C 和 C99 标准,上述代码的预处理输出应该是什么?

在我看来,这应该被评估为1;但是,运行 上述示例通过 gcc -Eclang -E 产生以下结果:

    #define BAR 1
BAR

您的代码无效

ISO/IEC 9899:2011,第 6.10 节预处理指令:

A preprocessing directive consists of a sequence of preprocessing tokens that satisfies the following constraints: The first token in the sequence is a # preprocessing token that (at the start of translation phase 4) is either the first character in the source file (optionally after white space containing no new-line characters) or that follows white space containing at least one new-line character.

标准草案“ISO/IEC 9899:201x 委员会草案 — 2011 年 4 月 12 日 N1570”第 6.10 节实际上包含一个示例:

EXAMPLE In:

#define EMPTY 
EMPTY # include <file.h>

the sequence of preprocessing tokens on the second line is not a preprocessing directive, because it does not begin with a # at the start of translation phase 4, even though it will do so after the macro EMPTY has been replaced.

它告诉我们“......第二行是不是预处理指令......”

所以对于你的代码

FOO #define BAR 1

不是 预处理指令,这意味着只有 FOO 将被替换并且 BAR 将 不是 被定义。因此预处理器的输出是:

 #define BAR 1
BAR

此示例实际出现在标准 (C17 6.10/8) 中:

EXAMPLE In:

#define EMPTY
EMPTY # include <file.h>

the sequence of preprocessing tokens on the second line is not a preprocessing directive, because it does not begin with a # at the start of translation phase 4, even though it will do so after the macro EMPTY has been replaced.

所以您从 gcc -E 看到的输出是正确的。 (注意:此处的空格数量并不重要,在翻译的那个阶段,程序已被翻译成一系列 预处理标记 ;输出中不同数量的空格只是一个gcc -E 工作原理的人工制品)。