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

  1. 在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

posted @ 2021-07-18 14:33  TruthHell  阅读(21108)  评论(0编辑  收藏  举报