如何修复 C 错误 'false undeclared'

问题:

你有类似这样的 C 代码

main.c
bool mybool = false;

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

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

解决方案

添加

main_fixed.c
#include <stdbool.h>

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

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


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