gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:40:24 26 4
gpt4 key购买 nike

我刚刚注意到 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;

(海湾合作委员会 stdint.hstdbool.h )

最佳答案

stdbool.hbool 定义为宏,因为 C 标准 ( section 7.18 ) 规定 bool 应定义为宏,并且 stdint.hintN_t 等定义为 typedef,因为 C 标准 (section 7.20) 规定 intN_t 等应定义为 typedef。

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

Notwithstanding the provisions of 7.1.3, a program may undefine and perhaps then redefine the macros bool, true, and false.

如果 bool 是一个 typedef 而 truefalse 是,我不知道,enum 常量,他们不可能允许你这样做,因为没有办法撤销这些类型的声明。

好的,为什么 C 委员会要允许你这样做?这更具推测性,但可能出于同样的原因,他们添加了 stdbool.h_Bool 而不是制作 bool, truefalse 关键字,就像它们在 C++ 中一样:他们希望保持与定义了 booltruefalse 本身,即使这些程序使用包含 stdbool.h...

的第三方 header

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

关于c - 为什么主要编译器对 stdint.h 使用 typedef 而对 stdbool.h 使用 #define?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46797609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com