gpt4 book ai didi

c - 在 C99 的宏中使用 true 和 false

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:12 25 4
gpt4 key购买 nike

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

ENABLE_LOGGING=true

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

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

事实证明这不能可靠地工作。有时使用包含代码的LOG,有时使用空的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

关于c - 在 C99 的宏中使用 true 和 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38847323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com