为什么主要编译器对 stdint.h 使用 typedef 而对 stdbool.h 使用 #define?

2024-04-19

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

例子:clang 的 stdint.h https://clang.llvm.org/doxygen/stdint_8h_source.html

 #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 的 stdbool.h https://clang.llvm.org/doxygen/stdbool_8h_source.html

#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.h https://github.com/gcc-mirror/gcc/blob/1cb6c2eb3b8361d850be8e8270c597270a1a7967/gcc/ginclude/stdint-gcc.h and 标准布尔.h https://github.com/gcc-mirror/gcc/blob/1cb6c2eb3b8361d850be8e8270c597270a1a7967/gcc/ginclude/stdbool.h)


stdbool.h定义bool作为宏,因为 C 标准 (第7.18节 http://port70.net/%7Ensz/c/c11/n1570.html#7.18) says bool应被定义为宏,并且stdint.h定义intN_t等作为 typedef,因为 C 标准(第7.20节 http://port70.net/%7Ensz/c/c11/n1570.html#7.20) says intN_t等应定义为 typedef。

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

尽管有规定7.1.3 http://port70.net/%7Ensz/c/c11/n1570.html#7.1.3,程序可能会取消定义,然后可能会重新定义宏 bool、true 和 false。

If bool是一个 typedef 和true and false是,我不知道,enum常量,他们不可能允许你这样做,因为没有办法撤消这些类型的声明。

好吧,为什么C委员会要允许你这么做呢?这更具推测性,但可能出于同样的原因他们补充说stdbool.h and _Bool而不是做bool, true, and false与 C++ 中的关键字一样:他们希望保持与定义的旧程序的兼容性bool, true, and false本身,即使这些程序使用第三方标头,其中包括stdbool.h...

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么主要编译器对 stdint.h 使用 typedef 而对 stdbool.h 使用 #define? 的相关文章

随机推荐