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

时间:2017-10-17 19:16:45

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

我刚注意到gcc和clang似乎都对stdint.h使用typedef,而对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

2 个答案:

答案 0 :(得分:19)

stdbool.hbool定义为宏,因为C标准(section 7.18)表示bool应定义为宏,stdint.h定义{{ 1}}等作为typedef,因为C标准(section 7.20)表示intN_t等应定义为typedef。

好的,为什么C标准说这些东西?我无法肯定地告诉你,但有一条线索在第7.18节第4段:

  

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

如果intN_t是typedef且booltrue是,我不知道,false常量,他们不能允许你这样做,因为有无法撤消这些声明。

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

此类向后兼容性问题不适用于stdbool.h定义的类型;一些系统提供(一些)作为扩展,但它们总是typedef。

答案 1 :(得分:1)

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

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

  

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

     

2)宏

     

bool

     

扩展为_Bool

相关问题