【问题标题】:Why do major compilers use typedef for stdint.h but use #define for stdbool.h?为什么主要编译器对 stdint.h 使用 typedef 而对 stdbool.h 使用 #define?
【发布时间】:2018-03-29 14:03:34
【问题描述】:

我刚刚注意到 gcc 和 clang 似乎都对 stdint.h 使用 typedefs 而对 stdbool.h 使用 #define。

示例:clang's stdint.h

 #ifdef __INT8_TYPE__
 #ifndef __int8_t_defined  /* glibc sys/types.h also defines int8_t*/
 typedef __INT8_TYPE__ int8_t;
 #endif /* __int8_t_defined */
 typedef __UINT8_TYPE__ uint8_t;
 # define __int_least8_t int8_t
 # define __uint_least8_t uint8_t
 #endif /* __INT8_TYPE__ */

clang's stdbool.h

#ifndef __cplusplus
#define bool _Bool
#define true 1
#define false 0
#elif defined(__GNUC__) && !defined(__STRICT_ANSI__)
/* Define _Bool, bool, false, true as a GNU extension. */
#define _Bool bool
#define bool  bool
#define false false
#define true  true
#endif

为什么不是typedef _Bool bool;

(gcc stdint.hstdbool.h)

【问题讨论】:

  • 不是同一个问题,但你可能会觉得它很有趣:stackoverflow.com/questions/1666353/…
  • 布尔求值在有人决定不使用之前运行得非常好,并将truefalse 粘贴在顶部。问题是,任何值不是 C 中的 0true。我从不使用布尔类型,我从不使用 truefalse,因为这些属性是 C 条件测试中固有的。
  • @WeatherVane 显然我遇到了一些使用bool 类型而不是整数时翻译效率更高的代码。所以我猜至少有些编译器看到了差异。
  • @WeatherVane:因为不管你认为自己有多男子气概,其他编码人员更喜欢看到bool is_enabled 而不是int is_enabled,因为前者更清楚地传达了可接受值的语义。

标签: c include c-preprocessor language-lawyer typedef


【解决方案1】:

stdbool.hbool 定义为宏,因为 C 标准 (section 7.18) 说 bool 应定义为宏,而 stdint.hintN_t 等定义为 typedef,因为 C 标准 (@ 987654322@) 表示intN_t 等应定义为 typedef。

好的,为什么 C 标准会这样说?我不能肯定地告诉你,但在第 7.18 节第 4 段中有一个线索:

尽管有7.1.3 的规定,程序可能会取消定义并可能重新定义宏 bool、true 和 false。

如果 bool 是 typedef 并且 truefalseenum 常量,我不知道,他们不可能允许你这样做,因为没有办法撤消这些各种声明。

好的,为什么 C 委员会要允许你这样做?这更具推测性,但可能出于同样的原因,他们添加了 stdbool.h_Bool,而不是像在 C++ 中那样制作 booltruefalse 关键字:他们希望保持与旧的兼容性自己定义了booltruefalse 的程序,即使这些程序使用包含stdbool.h 的第三方标头...

没有这种向后兼容性问题适用于stdint.h 定义的类型;一些系统提供(其中一些)作为扩展,但它们始终是 typedef。

【讨论】:

    【解决方案2】:

    我认为这只是standard 的一部分。

    如果您转到第 253 页,在 “7.16 布尔类型和值” 下,它清楚地表明:

    1) 标题<stdbool.h> 定义了四个宏。

    2) 宏

    bool

    扩展到_Bool

    【讨论】:

    • 那么问题就变成了为什么标准会这样而不是typedef _Bool bool
    • 实际上,问题是“为什么主要编译器 [...]” - 对于 bool,答案是“因为标准是这样说的”。到目前为止是正确的,但只有一半的答案(“为什么<stdint.h> not 没有打开)......
    猜你喜欢
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 2018-12-21
    • 1970-01-01
    • 2011-08-25
    • 2014-08-07
    • 1970-01-01
    相关资源
    最近更新 更多