浅浅浅谈compile_commands.json

2025-4-13|2025-4-20
FollyCoolly
FollyCoolly
type
status
date
slug
summary
tags
category
icon
password

compile_commands.json 是什么

compile_commands.json 是一个 JSON 格式的编译数据库文件,用于记录项目中每个源文件的具体编译命令。它常见于使用 CMake 构建的 C/C++ 项目,并广泛用于工具链和编辑器插件中,比如 Clangd、YouCompleteMe、VSCode C++ 插件、clang-tidy、clang-format 等。
clangd emulates how clang would interpret a file. By default, it behaves roughly as clang $FILENAME, but real projects usually require setting the include path (with the -I flag), defining preprocessor symbols, configuring warnings etc. Often, a compilation database specifies these compile commands. clangd searches for compile_commands.json in parents of the source file.

compile_commands.json 的作用

简而言之,compile_commands.json 让工具知道:
  • 每个 .cpp.c 文件是如何被编译的
  • 用了哪些编译选项(比如 std=c++17, Iinclude, DDEBUG 等)
  • 用了哪些头文件路径、宏定义等等
这使得 IDE 或静态分析工具可以准确地还原出编译环境,从而提供更精准的:
  • 自动补全
  • 语法高亮
  • 代码跳转
  • 错误提示
  • 静态分析(如 clang-tidy

compile_commands.json 的生成

CMake

在生成构建目录时加上参数
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .. 这样会在 build 目录下生成一个 compile_commands.json 文件。 某些工具(比如 clangd)希望文件在项目根目录,这时候可以使用ln -s build/compile_commands.json .生成一个软连接。

Bazel

浅谈C++标准库智能指针的deleterC++中的空基类优化
Loading...