本文介绍了为什么主编译器对stdint.h使用typedef,而对stdbool.h使用#define?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我只是注意到gcc和clang似乎都对stdint.h使用typedef,但对stdbool.h使用#define。I just noticed that gcc and clang both appear to use typedefs for stdint.h but #define for stdbool.h.示例: 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'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。 h 和 stdbool.h )推荐答案 stdbool.h 定义 bool 作为宏,因为C标准(第7.18节)说 bool 应定义为宏, stdint.h 定义 intN_t 等作为typedef,因为C标准(第7.20节) )说 intN_t 等等应定义为typedef。stdbool.h defines bool as a macro because the C standard (section 7.18) says bool shall be defined as a macro, and stdint.h defines intN_t etc as typedefs because the C standard (section 7.20) says intN_t etc shall be defined as typedefs.好的,为什么C标准说这些东西?我无法确定,但有一条线索在第7.18节第4段:Okay, why does the C standard say these things? I cannot tell you for sure, but a clue is in section 7.18 paragraph 4:如果 bool 是typedef和是和 false 是,我不知道,枚举常数,他们不能允许你这样做,因为没有办法撤消这些声明。If bool were a typedef and true and false were, I dunno, enum constants, they couldn't have allowed you to do that, as there is no way to undo those kinds of declarations.好的,为什么C委员会想让你这样做?这更具有推测性,但可能出于同样的原因,他们添加了 stdbool.h 和 _Bool 而不是 bool , true ,以及 false 关键字,因为它们在C ++中:他们希望保持与定义 bool , true 和 false 的旧程序的兼容性code>他们自己,即使这些程序使用包含 stdbool.h的第三方标题 ... Okay, why does the C committee want to allow you to do that? This is even more speculative, but probably for the same reason they added stdbool.h and _Bool instead of making bool, true, and false keywords as they are in C++: they wanted to preserve compatibility with old programs that defined bool, true, and false themselves, even if those programs use third-party headers that include stdbool.h...没有这样的向后兼容性问题适用于 stdint.h 定义的类型;一些系统提供(一些)作为扩展,但它们总是typedef。No such backward compatibility concerns apply to the types defined by stdint.h; some systems provided (some) of them as extensions, but they were always typedefs. 这篇关于为什么主编译器对stdint.h使用typedef,而对stdbool.h使用#define?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-21 10:47