为什么主编译器对stdint.h使用typedef,而对stdbool.h使用#define?
我只是注意到gcc和clang似乎都对stdint.h使用typedef,而对stdbool.h使用#define。
例如: clang的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的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.h和stdbool.h )
stdbool.h
将bool
定义为宏,因为C标准( 第7.18节 )说bool
应定义为宏, stdint.h
将intN_t
等定义为typedef,因为C标准( 第7.20节 )说intN_t
等应定义为typedef 。
好吧,为什么C标准说这些东西? 我不能肯定地告诉你,但有一条线索在第7.18节第4段:
尽管有7.1.3的规定,程序可能会取消定义,然后重新定义宏bool,true和false。
如果bool
是一个typedef而且true
和false
是,我不知道, enum
常量,他们不能允许你这样做,因为没有办法撤消那种声明。
好的,为什么C委员会想要允许你这样做? 这更具推测性,但可能出于同样的原因,他们添加了stdbool.h
和_Bool
而不是像C ++中那样制作bool
, true
和false
关键字:他们希望保持与定义bool
, true
和自己是false
,即使这些程序使用包含stdbool.h
的第三方标题…
没有这样的向后兼容性问题适用于stdint.h
定义的类型; 一些系统提供(一些)作为扩展,但它们总是typedef。
我认为这只是标准的一部分。
如果你转到第253页,在“7.16布尔类型和值”下 ,它清楚地说:
1)头文件
定义了四个宏。
2)宏
bool
扩展为
_Bool
。