避免 IntelliSense 無法辨識非標準路徑中的 Header File
在撰寫 C/C++ 程式時,可能會從非標準路徑中引入 Header File,例如 SystemC 的 Header File 通常會放在 /usr/local/systemc/include 目錄下,並且透過 -I 參數指定這個路徑。我們可以在 Makefile 中設定這個路徑,讓編譯器能夠正確辨識這些非標準路徑中的 Header File。
而 IntlliSence 可能無法辨識這些非標準路徑中的 Header File,造成在 Text Editor 或 IDE 中無法正確顯示提示,或產生惱人的錯誤提示。本文將介紹如何在 Makefile 或 CMake 中設定這些非標準路徑中的 Header File,讓 IntelliSense 能夠正確辨識。
compile_commands.json
compile_commands.json 是一個紀錄每一個編譯單元 (Compilation Unit) 所使用編譯指令的 JSON 檔案。我們可以利用該檔案來告訴 IntelliSense,使 IntelliSense 能夠正確辨識非標準路徑中的 Header File。
使用 compile_commands.json 的好處是,我們可以讓不同的 IntelliSense Engine (如 Clangd) 共用這個檔案,以減少為每一個 IntelliSense Engine 設定路徑的麻煩。
在 CMake 中設定 compile_commands.json
在 CMake 中,我們可以透過 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON 參數來產生 compile_commands.json 檔案。
可以透過在編譯時手動加入該參數,如下所示
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..
或是在 CMakeLists.txt 中加入以下設定
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
即可在編譯完成後,產生 compile_commands.json 檔案,供 IntelliSense 使用。
在 Makefile 中設定 compile_commands.json
在 Makefile 中,我們可以透過 Bear 這個工具來產生 compile_commands.json 檔案。
首先,安裝 Bear 工具
sudo apt-get install bear # Ubuntu
並使用 Bear 來執行編譯指令,如下所示
bear -- make
即可在編譯完成後,產生 compile_commands.json 檔案,供 IntelliSense 使用。
Vscode IntelliSense 設定
若使用 Vscode 之 C/C++ Extension 中的 IntelliSense,可以在 .vscode/c_cpp_properties.json 中加入以下設定,讓 IntelliSense 能夠正確辨識 compile_commands.json 檔案
{
"configurations": [
{
"name": "Linux",
"compileCommands": "${workspaceFolder}/compile_commands.json" // Path to compile_commands.json
}
],
"version": 4
}