llvm学习(十):修复 macOS Catalina 缺失 /usr/include 导致的clang无法使用

今天升了macOS10.15,发现自己编译的llvm和clang坏掉了,重新编译也没用,而自带的/usr/clang是没有问题的,发现是 /usr/include 缺失。

==2020年11月19日:big sur 无法修改/usr/include,==

==2020年11月20日:使用cmake初始化时,添加-DDEFAULT_SYSROOT=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk,重新编译,即可解决==

一、背景

Command Line Tools 10.13系列,是拥有/usr/include目录的,之前一直在用。但是在macOS 10.15上无法安装它,就很气。 Command Line Tools 10.14系列,砍掉了32位的编译环境,也砍掉了/usr/include。 macOS 10.15砍掉了 32 位的运行环境,将 / 挂载为 read-only。 而自己编译的llvm+clang是不会主动去寻找 MacOSXSDK的头文件的,就出现了找不到头文件的情况。

二、修复过程(中英双语,中文更简单、英文更详细)

人肉diff 一下曾经的

/usr/include

和 现在的

/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include

发现后者比前者多出少量的.h 文件,但缺少 c++目录。 而现在的 c++目录在

/Library/Developer/CommandLineTools/usr/include/c++

因此思路很简单

1、恢复 c++

1
sudo ln -s /Library/Developer/CommandLineTools/usr/include/c++ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++

2、重启到 recovery 关掉 SIP

3、重启到操作系统

1
2
sudo mount -uw /
sudo ln -s /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include /usr/include

4、重启到 recovery 开启 SIP

5、效果

1
2
➜  lsa /usr/include
lrwxr-xr-x 1 root wheel 63B 10 16 14:31 include -> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include

这时候/usr/include 下面就有 c 和 cpp 常用的头文件了,自己编译的 llvm 和 clang 也就可以正常使用了

三、Repair it

Since Command-Line-Tools >= 10.14, there is no /usr/include path. And after macOS Catalina, ‘/‘ partition is read-only. So I finally fix it by myself. I diff the /usr/include for 10.13 and /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include for 10.15. The only difference is that: - Most of them are the same. - 10.15 has more header files, maybe some new feature. - 10.13 has c++ directory, which is /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++ in macOS 10.15. So do the following things:

  1. add c++ headers

sudo ln -s /Library/Developer/CommandLineTools/usr/include/c++ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++

  1. reboot to recovery and disable SIP
  2. reboot to desktop,

sudo mount -uw / sudo ln -s /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include /usr/include

  1. reboot to recovery and enable SIP.
  2. result:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
➜  lsa /usr/include
lrwxr-xr-x 1 root wheel 63B 10 16 14:31 include -> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include

➜ /tmp clang -v test.c
clang version 8.0.0 (tags/RELEASE_800/final)
Target: x86_64-apple-darwin19.0.0
Thread model: posix
........
#include "..." search starts here:
#include <...> search starts here:
/usr/local/include
/Users/leadroyal/pllvm/r/lib/clang/8.0.0/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.

四、相关链接

https://github.com/Homebrew/homebrew-core/issues/45061
https://discourse.brew.sh/t/clang-can-no-longer-find-usr-include-header-files-fatal-error-stdlib-h-file-not-found/4523/7