C翻译阶段4

C translation phase 4

最近我遇到了以下问题。我的实现是这样的:

#define MY_CODE_VERSION PROJ_VERSION
#include "project.h"
if (3 != MY_CODE_VERSION)

PROJ_VERSION 是在 project.h 中定义的。为什么我没有得到合辑 warning/error?因为我试图在编译器到达 #define MY_CODE_VERSION PROJ_VERSION.
行时在宏上定义一些未知的东西 我从 ANSI C 查看了这些阶段,但我无法弄清楚原因(编译器的实际行为,在哪个阶段 MY_CODE_VERSION 取 PROJ_VERSION 的值)。

我的假设是,此替换仅发生在“#if (3 != MY_CODE_VERSION)”行,此时编译器已通过包含 PROJ_VERSION 获知 project.h 以上。

提前致谢

我不会散列你已经知道的东西。你显然 不知道的事情:

6.10.3.4 Rescanning and further replacement

  1. After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing tokens are removed. Then, the resulting preprocessing token sequence is rescanned, along with all subsequent preprocessing tokens of the source file, for more macro names to replace.
  2. If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. Furthermore, if any nested replacements encounter the name of the macro being replaced, it is not replaced. These nonreplaced macro name preprocessing tokens are no longer available for further replacement even if they are later (re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced.
  3. The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one, but all pragma unary operator expressions within it are then processed as specified in 6.10.9 below.

简而言之,一旦扩展了宏并执行了所有字符串化器和连接,生成的 "thing" 将再次扫描以查找更多要替换的内容。如果找到相同的名称,则替换。

所以您看到的是标准定义的。