--- title: macOS 編譯 C++ 發生錯誤:`__availability` file not found 修復教學 tags: - macOS - Xcode - clang++ - C++ - Command Line Tools - VS Code - libc++ - 編譯錯誤 - Xcode-select - 開發環境 - __availability - fatal error - 環境設定 - macOS開發 --- # macOS 編譯 C++ 發生錯誤:`__availability` file not found 修復教學 ## ❗ 錯誤訊息 在 macOS 中使用 clang++ 編譯 C++ 程式時,出現下列錯誤: ``` fatal error: '__availability' file not found ``` 這通常伴隨如下堆疊: ``` In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/... ``` --- ## 📌 錯誤原因總結 | 問題來源 | 說明 | |----------|------| | ❌ macOS 安裝了「壞掉的 Command Line Tools」 | 裡面的 C++ 標頭檔(如 `<__availability>`)缺失或不完整。 | | ❌ `clang++` 編譯時使用了錯誤的標頭來源 | 優先搜尋 `/Library/Developer/CommandLineTools`,導致出錯。 | | ✅ 即使有安裝 Xcode,也不一定會正確使用 | 必須手動設定並清除錯誤路徑。 | --- ## ✅ 解法步驟 ### 1. 刪除壞掉的 Command Line Tools ```bash sudo rm -rf /Library/Developer/CommandLineTools ``` ### 2. 指定使用完整 Xcode 工具鏈 ```bash sudo xcode-select -s /Applications/Xcode.app/Contents/Developer ``` ### 3. 關閉並重新開啟 Terminal 或 VS Code 這是為了清除舊的環境快取。 ### 4. 測試編譯 ```bash clang++ -std=c++17 -o student student.cpp ./student ``` > 如仍需指定 SDK,可加上: ```bash clang++ -std=c++17 -isysroot $(xcrun --show-sdk-path) -o student student.cpp ``` --- ## 🔍 驗證是否修好 ```bash clang++ -E -x c++ - -v < /dev/null | grep CommandLineTools ``` ✅ 沒有輸出代表成功移除錯誤路徑! --- ## 🧠 小結 這個錯誤其實 **非常常見**,尤其在以下情況: - macOS 升級或重裝 Command Line Tools 後 - 使用 VS Code 搭配 clang++ 編譯 C++ - 有安裝 Xcode 卻沒有設定正確的 xcode-select - 編譯時無意間使用壞掉的 C++ 標頭來源 --- 按照本教學執行一次清理與修復,即可解決問題,讓你在 macOS 上安心使用 clang++ 編譯 C++ 程式。 Happy coding! 🍎💻✨