在 C99 的宏中使用 true 和 false

Using true and false in macros in C99

我正在使用支持 C99 子集的自定义 gcc 编译器编写一些代码。使用编译器选项我定义了一个这样的宏:

ENABLE_LOGGING=true

我在我的代码中这样使用它:

#if ENABLE_LOGGING
#define LOG(foo) { log(foo); }
#else
#define LOG(foo)
#endif

事实证明这不能可靠地工作。有时使用 LOG 包含代码,有时使用 emtpy LOG(相同的项目,相同的编译器设置)。

将宏参数更改为:

ENABLE_LOGGING=1

一切正常。

我知道预处理器可能不知道 true。但是,为什么它在大多数时候都有效?为什么我在编译期间没有收到任何警告或错误?

#define hehe true
#if hehe
#error hehe
#else
#error haha
#endif

#error haha 因为 hehe 扩展为 truetrue 将被 0 替代,因为

§6.10.1¶4 all remaining identifiers (including those lexically identical to keywords) are replaced with the pp-number 0

但是如果你碰巧 #include <stdbool.h> 在你的 #if 之前,它会 #error hehe,因为

§7.18 The header defines four macros. …

¶3 The remaining three macros are suitable for use in #if preprocessing directives. They are true which expands to the integer constant 1