結論
- MacOS をメジャーアップデートしてたら、CommandLineTools をアップデートしましょう
CommandLineTools がアップデートできない場合、以下の手順でインストールし直しましょう
>> rm -rf /Library/Developer/CommandLineTools >> xcode-select --install
- できない場合、More - Downloads - Apple Developerから最新版をダウンロードしましょう。
環境
経緯
きっかけは競技プログラミングの問題を1年ぶりに解こうとしたとき
>> g++-11 -D_GLIBXX_DEBUG ./main.cpp
In file included from /usr/local/Cellar/gcc/11.2.0_3/include/c++/11/x86_64-apple-darwin20/bits/stdc++.h:33,
from ./main.cpp:1:
/usr/local/Cellar/gcc/11.2.0_3/include/c++/11/cassert:44:10: fatal error: assert.h: No such file or directory
44 | #include <assert.h>
| ^~~~~~~~~~
compilation terminated.
ヘッダーファイルが見つからずコンパイルに失敗していました。
gcc, g++ は想定した通り brew でインストールした先を指しています。
>> which gcc
/usr/local/bin/gcc
>> which g++
/usr/local/bin/g++
もう少し細かくコンパイラのオプションを見てみます。
>> g++-11 -v
Using built-in specs.
COLLECT_GCC=g++-11
COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc/11.2.0_3/bin/../libexec/gcc/x86_64-apple-darwin20/11/lto-wrapper
Target: x86_64-apple-darwin20
Configured with: ../configure --prefix=/usr/local/opt/gcc --libdir=/usr/local/opt/gcc/lib/gcc/11 --disable-nls --enable-checking=release --with-gcc-major-version-only --enable-languages=c,c++,objc,obj-c++,fortran,d --program-suffix=-11 --with-gmp=/usr/local/opt/gmp --with-mpfr=/usr/local/opt/mpfr --with-mpc=/usr/local/opt/libmpc --with-isl=/usr/local/opt/isl --with-zstd=/usr/local/opt/zstd --with-pkgversion='Homebrew GCC 11.2.0_3' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --enable-libphobos --build=x86_64-apple-darwin20 --with-system-zlib --disable-multilib --with-native-system-header-dir=/usr/include --with-sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX11.sdk
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 11.2.0 (Homebrew GCC 11.2.0_3)
ここでコマンドラインツールを指定しているようです。
--with-sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX11.sdk 。一応存在しているか見てみます。
>> ls /Library/Developer/CommandLineTools/SDKs/
. .. MacOSX.sdk MacOSX10.15.sdk
...ないですね...
ここで思い当たったのが、MacOSのメジャーアップデートです。かなり前にやっていたのですが、CommandLineTools の更新はしていませんでした。しかも、その後に gcc のアップデートをしています。よって、gcc は最新のOSバージョンを見て CommandLineTools を探していたのかと推測されます。その一方、ローカルには古いOSバージョンの CommandLineTools しかなかったため、ヘッダーを見つけることができなかったと思われます。(ここは自分の推測なので、間違っていたらご指摘ください!)
解決
xcode-select --install
はすでにインストールされているとの表示。
>> xcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
言われた通りsoftwareupdateを見てもコマンドラインツールのアップデートは存在していませんでした。
そこで、無理矢理コマンドラインツール一式を削除し、インストールし直すことを試します。
>> rm -rf /Library/Developer/CommandLineTools
>> xcode-select --install
xcode-select: note: install requested for command line developer tools
このログが出ますがインストールされません。
よくわからないのですが、OSが最新バージョンではないためでしょうか。More - Downloads - Apple Developerから最新版をダウンロードしたところ、無事にコンパイルができました...!
参考
この辺を大変参考にさせていただきました。