Compilation error: "stddef.h: No such file or directory"

Compilation error: "stddef.h: No such file or directory"

每当我尝试编译这段代码时,它总是以这个错误结束:

    In file included from /usr/include/wchar.h:6:0,
             from /usr/lib/gcc/i686-pc-cygwin/4.9.2/include/c++/cwchar:44,
             from /usr/lib/gcc/i686-pc-cygwin/4.9.2/include/c++/bits/postypes.h:40,
             from /usr/lib/gcc/i686-pc-cygwin/4.9.2/include/c++/iosfwd:40,
             from /usr/lib/gcc/i686-pc-cygwin/4.9.2/include/c++/ios:38,
             from /usr/lib/gcc/i686-pc-cygwin/4.9.2/include/c++/ostream:38,
             from /usr/lib/gcc/i686-pc-cygwin/4.9.2/include/c++/iostream:39,
             from test.cpp:1:
    /usr/include/sys/reent.h:14:20: fatal error: stddef.h: No such file or directory
    #include <stddef.h>
                ^
    compilation terminated.

我试图编译的代码是:

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World! :D";
    return 0;
}

错误是因为你的gcc-core包和gcc-g++不是同一个版本。要么降级其中一个来解决问题,要么更新两个库。更新这两个库是推荐的方法。

我在全新的 MinGW 安装中遇到了这个错误,它与 "Prasanth Karri" 当前接受的答案中提到的已安装软件包无关。在我的例子中,问题是由我的 Makefile 中的 -nostdinc 引起的。我实际上只在为不同的目标平台构建时(而不是在使用 MinGW 时)需要那个编译器标志,所以我通过从 MinGW 构建中删除那个标志来解决这个问题。

当我将用 C 编写的软件库合并到现有的演示项目中时(使用 C++ mbed 库),我遇到了这个问题。 demo工程本来可以编译的,但是我自己替换现有的主文件后,就出现了这个错误。

此时我还没有想到我需要的mbed库是用C++写的。我自己的主文件是一个 .c 文件,#include mbed header 文件。结果,我使用我的普通 C 源代码,就好像它是 C++ 源代码一样。因此,用于编译我的主文件的编译器是 C 编译器。 然后,此 C 编译器遇到模块 that actually does not exist(在其范围内)的 #include,因为它不是 C++ 编译器。

只有在检查构建日志的输出后,我才意识到各种源 C 和 C++ 文件是由不止一个编译器(c++ 编译器)编译的。该项目使用编译器 arm-none-eabi-c++ 和 arm-none-eabi-gcc(用于嵌入式系统),如下所示。

编译日志:

Building file: ../anyfile.cpp
Invoking: MCU C++ Compiler
arm-none-eabi-c++ <A lot of arguments> "../anyfile.cpp"
Finished building: ../anyfile.cpp

Building file: ../main.c
Invoking: MCU C Compiler
arm-none-eabi-gcc <A lot of arguments> "../main.c"
In file included from <Project directory>\mbed/mbed.h:21:0,
                 from ../main.c:16:
<Project directory>\mbed/platform.h:25:19: fatal error: cstddef: No such file or directory
compilation terminated.

当然是在 C++ 环境中 cstddef exists, but in a C environment cstddef doesn't exist, in stead it's just C's implementation of stddef.

换句话说,C编译器中不存在cstddef。 我通过将我的 main.c 文件重命名为 main.cpp 解决了这个问题,其余代码也顺利编译。

TLDR/Conclusion:构建 C++ 项目时,避免将 C 文件与 C++ 文件(源和 headers)混合。如果可能,将 .c 文件重命名为 .cpp 文件,以便在需要时使用 C++ 编译器而不是 C 编译器。

我安装了 codeblocks 和 mingw 编译器,然后我将 mingw 文件夹从 codeblocks 复制到 C 盘并添加 C\mingw\bin 到环境变量。

如果您尝试编译并看到类似 "fatal error: stddef.h: No such file or directory" 的消息,则错误是因为您的 gcc-core 和 gcc-g++ 包的版本不同。重新运行 Cygwin 安装并确保 select gcc-core 和 gcc-g++ 的最高编号版本。

为了更新它,请按照下面的操作。 如果您使用 Windows,只需 运行 命令提示符或 powershell

更新包列表:mingw-get update

更新包列表后,运行:mingw-get upgrade

来源:How to update GCC in MinGW on Windows?

用MinGW安装C++编译器后我也遇到了这个问题。显然,您还必须安装 mingw32-base。转到 C:/MinGW/bin/mingw-get.exe(我的路径)并在基本设置选项卡中检查它是否安装。