如何修复 C 错误 'NULL undeclared'

问题:

你有类似这样的 C 代码

main.c
char* ptr = NULL;

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

error_message.txt
main.c: In function ‘main’:
main.c:3:17: error: ‘NULL’ undeclared (first use in this function)
     void* ptr = NULL;
                 ^~~~
main.c:3:17: note: each undeclared identifier is reported only once for each function it appears in

解决方案

添加

fix_null_error.c
#include <stddef.h>

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

此错误的原因是 NULL 不是在 C 本身中定义的,而只在 stddef.h 中。


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