如何修复 C 错误 'true undeclared'

问题:

你有类似这样的 C 代码

true_undeclared_example.c
bool mybool = true;

但当你尝试编译它时,你看到类似这样的错误消息

true_undeclared_output.txt
main.c: In function ‘main’:
main.c:2:5: error: unknown type name ‘bool’; did you mean ‘_Bool’?
     bool mybool = true;
     ^~~~
     _Bool
main.c:2:19: error: ‘true’ undeclared (first use in this function)
     bool mybool = true;
                   ^~~~
main.c:2:19: note: each undeclared identifier is reported only once for each function it appears in

解决方案

添加

include_stdbool.c
#include <stdbool.h>

在错误发生的源文件顶部。

此错误的原因是 bool 不是 C 中的标准类型(如 intchar),而只在 stdbool.h 中。此外,truefalsestdbool.h 中声明。


Check out similar posts by category: C/C++, GCC Errors