Bazel 如何生成 clangd/clang-tidy 所需的 compile_commands.json

发布时间 2023-08-06 17:04:31作者: Zijian/TENG

VSCode 中如何使用 clang-tidy

  1. 安装 clangd 插件
  2. 禁用 ms-cpp 插件(VSCode 会自动提示有冲突)
  3. 生成 clangd 所需的 compile_commands.json 文件

如何生成 compile_commands.json 文件

  1. 修改 WORKSPACE,添加以下内容
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "hedron_compile_commands",

    # 建议把下面两处 commit hash 换成 github 上最新的版本
    url = "https://github.com/hedronvision/bazel-compile-commands-extractor/archive/ed994039a951b736091776d677f324b3903ef939.tar.gz",
    strip_prefix = "bazel-compile-commands-extractor-ed994039a951b736091776d677f324b3903ef939",
)

load("@hedron_compile_commands//:workspace_setup.bzl", "hedron_compile_commands_setup")
hedron_compile_commands_setup()
  1. 在 BUILD 文件中增加一个用于生成 compile_commands.json 文件的 target
load("@hedron_compile_commands//:refresh_compile_commands.bzl", "refresh_compile_commands")

refresh_compile_commands(
    name = "refresh_compile_commands",
    # 指定目标 target 及其编译选项/参数(.bazelrc 中已有的参数/选项无需重复添加)
    targets = {
      "//src/my_component1:my_executable1": "--config=aarch64_qnx",
      "//src/my_component2:my_executable2": "--config=aarch64_linux",
    },
)
  1. 运行 bazel run 命令生成 compile_commands.json 文件
bazel run :refresh_compile_commands

注意事项

  • 需要保证能够访问 github

参考链接