1. 程式人生 > 其它 >vscode使用compile_commands.json

vscode使用compile_commands.json

vscode使用compile_commands.json

背景

vscode+cmake可以實現C/C++專案開發和構建。可以在vscode上裝以下幾個外掛:

CMake Tools外掛能夠給C/C++外掛提供資訊,實現IntelliSense、程式碼補全、註釋瀏覽、檔案轉跳等功能。一般在第一次使用CMake Tools外掛時會出現如下提示:

Allow之後會在當前工作目錄的.vscode/settings.json檔案(即當前工作目錄的設定檔案,會覆蓋使用者設定檔案)中新增:

{
    "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools"
}

當然,也可以在C/C++外掛的配置檔案.vscode/c_cpp_properties.json中手動指定configurationProvider

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "gnu11",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "gcc-x64",
            "configurationProvider": "ms-vscode.cmake-tools"
        }
    ],
    "version": 4
}

這樣C/C++外掛就能正常工作了,不用自己指定.vscode/c_cpp_properties.jsonincludePathdefines
除了以上兩種方式以外,還有另一種方式:

指定compile_commands.json

  1. 讓cmake生成compile_commands.json,需要在執行cmake時新增引數-DCMAKE_EXPORT_COMPILE_COMMANDS=True或者在CMakeLists.txt中新增set(CMAKE_EXPORT_COMPILE_COMMANDS True)。例子:假設在~目錄下有一個hello的專案
cd ~/hello
mkdir build
cd build
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=True ..

會在~/hello/build下生成compile_commands.json
2. 在vscode中開啟~/hello目錄,配置.vscode/c_cpp_properties.json。指定compileCommands為上一步的~/hello/build/compile_commands.json

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [],
            "defines": [],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "gnu11",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "gcc-x64",
            "compileCommands": "~/hello/build/compile_commands.json"
        }
    ],
    "version": 4
}

這樣和指定configurationProvider是一樣的效果。

原理

  • configurationProvider

The ID of a VS Code extension that can provide IntelliSense configuration information for source files. For example, use the VS Code extension ID ms-vscode.cmake-tools to provide configuration information from the CMake Tools extension.

  • compileCommands

The full path to the compile_commands.json file for the workspace. The include paths and defines discovered in this file will be used instead of the values set for includePath and defines settings. If the compile commands database does not contain an entry for the translation unit that corresponds to the file you opened in the editor, then a warning message will appear and the extension will use the includePath and defines settings instead.

參考:

https://cmake.org/cmake/help/latest/variable/CMAKE_EXPORT_COMPILE_COMMANDS.html
https://code.visualstudio.com/docs/languages/cpp
https://code.visualstudio.com/docs/cpp/cmake-linux
https://code.visualstudio.com/docs/cpp/c-cpp-properties-schema-reference
https://code.visualstudio.com/docs/cpp/customize-default-settings-cpp
https://code.visualstudio.com/docs/cpp/configure-intellisense-crosscompilation
https://clang.llvm.org/docs/JSONCompilationDatabase.html