mac 下 clang++ 找不到头文件 stdlib.h

时间:2023-03-09 22:28:02
mac 下 clang++ 找不到头文件 stdlib.h

因为要用 openmp库,用 clang++ 编译 c++程序,出现了如下报错:

clang++ xx.cpp -o xx -fopenmp
/usr/local/Cellar/llvm/7.0.0/include/c++/v1/stdlib.h:94:15:
fatal error: 'stdlib.h' file not found
#include_next <stdlib.h>
^

探究原因:

include_next是在当前文件所在的路径后面的路径(一般有多个搜索路径)里搜索头文件。

报错说明 clang++的 include 搜索路径里/usr/local/Cellar/llvm/7.0.0/include/c++/v1/ 后面的路径中不存在stdlib.h文件。

网上的解决方案

xcode-select install

没有用。

使用命令查看 clang++的 include 搜索路径(#include <...> search starts here: 后面)。

clang++ -E -x c++ - -v < /dev/null

可以看到这些

 /usr/local/Cellar/llvm/7.0.0/include/c++/v1
/usr/include/c++/v1
/usr/local/include
/usr/local/Cellar/llvm/7.0.0/lib/clang/7.0.0/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)

发现忽略了不存在的 /usr/include

因为当前的 clang++是用 brew 安装的 llvm 自带的。

尝试了卸载 llvm

brew remove llvm

这时系统里还有 clang++,看起来是 Xcode 的工具链里的。

这时再执行clang++ -E -x c++ - -v < /dev/null可以看到

 /usr/local/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/10.0.0/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks (framework directory)

因为要用 openmp,所以还得用 brew 安装的 llvm。就又安装回来了

brew install llvm

然后通过添加软链接的方式解决问题。

ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include /usr/include/c++/v1

因为MacOSX10.14.sdk实际上是指向MacOSX.sdk的软链接,所以直接用MacOSX.sdk即可。