C 中的#ifndef 被忽略了吗?
#ifndef in C being ignored?
我有一些代码,我只想在定义了 DEBUG 时进行日志记录。所以我虽然可以用注释字符串“//”替换令牌(此处:"DEBUGLOG")。但是怎么办?
#ifndef DEBUG
#define DEBUGLOG //
#endif
[...]
DEBUGLOG printf("Debug String"\n);
[...]
代码中其他地方没有 DEBUG 定义。但是我的 gcc 编译了这一行并且程序本身执行了 printf();
为什么?
我试图像这样将它包含在括号中,但出现编译错误:
#ifndef DEBUG
#define DEBUGLOG "//"
#endif
这是编译器消息:
beispiel.c:45:10: error: expected ‘;’ before ‘printf’
DEBUGLOG printf("Debug String"\n);
^
有什么提示吗?
如果您查找 Phases of translation,您会发现执行预处理器的阶段(阶段 4)是 在 注释被替换的阶段之后白色 space 字符(第 3 阶段)。
Phase 3
1) The source file is decomposed into comments, sequences of whitespace characters (space, horizontal tab, new-line, vertical tab, and form-feed), and preprocessing tokens, which are the following
...
2) Each comment is replaced by one space character
Phase 4
1) Preprocessor is executed.
因此在第 3 阶段,行:
#define DEBUGLOG //
变成:
#define DEBUGLOG
在第 4 阶段,行:
DEBUGLOG printf("Debug String"\n);
变成:
printf("Debug String"\n);
这就是你的 printf
被执行的原因。
当你把它引号 ("//"
) 时,那一行变成:
"//" printf("Debug String"\n);
引号 (""
) 不会被删除。这是编译器错误。
我有一些代码,我只想在定义了 DEBUG 时进行日志记录。所以我虽然可以用注释字符串“//”替换令牌(此处:"DEBUGLOG")。但是怎么办?
#ifndef DEBUG
#define DEBUGLOG //
#endif
[...]
DEBUGLOG printf("Debug String"\n);
[...]
代码中其他地方没有 DEBUG 定义。但是我的 gcc 编译了这一行并且程序本身执行了 printf();
为什么?
我试图像这样将它包含在括号中,但出现编译错误:
#ifndef DEBUG
#define DEBUGLOG "//"
#endif
这是编译器消息:
beispiel.c:45:10: error: expected ‘;’ before ‘printf’
DEBUGLOG printf("Debug String"\n);
^
有什么提示吗?
如果您查找 Phases of translation,您会发现执行预处理器的阶段(阶段 4)是 在 注释被替换的阶段之后白色 space 字符(第 3 阶段)。
Phase 3
1) The source file is decomposed into comments, sequences of whitespace characters (space, horizontal tab, new-line, vertical tab, and form-feed), and preprocessing tokens, which are the following
...
2) Each comment is replaced by one space characterPhase 4
1) Preprocessor is executed.
因此在第 3 阶段,行:
#define DEBUGLOG //
变成:
#define DEBUGLOG
在第 4 阶段,行:
DEBUGLOG printf("Debug String"\n);
变成:
printf("Debug String"\n);
这就是你的 printf
被执行的原因。
当你把它引号 ("//"
) 时,那一行变成:
"//" printf("Debug String"\n);
引号 (""
) 不会被删除。这是编译器错误。