为什么clang的stdbool.h包含#define false false

Ant*_*ois 60 c++ clang language-lawyer

在被编译器错误指向后,我注意到clang的stdbool.h文件包括(除其他外)以下行:

#define bool  bool
#define false false
#define true  true
Run Code Online (Sandbox Code Playgroud)

它们包含在一个间接#ifdef强制执行的块中__cplusplus,因此c ++标记即使stdbool.h是C头也是如此.

那些定义需要什么?我想他们需要一些与预处理器相关的原因,但我有兴趣知道标准的哪个部分或者哪个技术原因使得clang必须包括那些.

nne*_*neo 50

stdbool.h是一个C头,而不是C++头.它不是通常在C++程序中,因为truefalse已经用C++关键字.

因此,如果C++程序包含stdbool.h它,则相当清楚地表明它是一个移植的C程序(例如,正在编译为C++的C程序).在这种情况下,stdbool.h根据GCCstdbool.h的评论,G ++支持在C++模式下作为GNU扩展:

/* Supporting <stdbool.h> in C++ is a GCC extension.  */
#define _Bool        bool
#define bool        bool
#define false        false
#define true        true

...

/* Signal that all the definitions are present.  */
#define __bool_true_false_are_defined        1
Run Code Online (Sandbox Code Playgroud)

同样,Clang stdbool.h在C++中支持与G ++的兼容性.这里有意定义这些值以匹配内置C++类型而不是传统的C99定义.它们被定义为宏,可能是为了提供与C99标准的一些兼容性,这要求:

标题应当载明下列:bool,true,false,__bool_true_false_are_defined.

应用程序可能会取消定义,然后可能重新定义宏bool,true和false.


Sha*_*our 18

它被添加到C++中支持GNU模式,我们可以从这个补丁中看到[cfe-commits] r115028:

当我们使用与GNU兼容的C++方言时,定义_Bool,bool,true和false宏.修复<rdar:// problem/8477819>.

所以gcc支持这个作为扩展,并且这个修改是为了支持该扩展.

虽然我找不到补丁中提到的原始问题报告.

这是不符合的,我们可以从草案C++ 11标准部分看到18.10其他运行时支持[support.runtime]:

标头<cstdbool>和标头<stdbool.h>不应定义名为bool,true或false的宏.

gcc并不意味着在GNU模式下严格遵守.

stdbool.h是C99的一部分,所以在C++ 11之前不支持C++标准,在附件D中说:

为了与C标准库和C Unicode TR兼容,C++标准库提供了25个C头,如表154所示

并包括<stdbool.h>.