TExcelTAD
Home › Modern CMake (with CTest & CPack) › Toolkit: VS Code, CLion & compile_commands.json

Toolkit: VS Code, CLion & compile_commands.json

Editors need to know how each file is compiled (include paths, definitions, standard) to offer completion, navigation and diagnostics. With CMake there are two machine-readable sources of that information: compile_commands.json, a simple list understood by clangd, clang-tidy and many other tools, and the CMake File API, a richer model IDEs use to show targets and run builds.

compile_commands.json

Set CMAKE_EXPORT_COMPILE_COMMANDS (Makefile and Ninja generators) and CMake writes the file into the build directory:

bash · try it yourself
mkdir -p ed/src && cd ed
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Ed LANGUAGES CXX)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_library(core STATIC src/core.cpp)
target_include_directories(core PUBLIC include)
target_compile_definitions(core PUBLIC CORE_API=1)
target_compile_features(core PUBLIC cxx_std_20)
add_executable(app src/main.cpp)
target_link_libraries(app PRIVATE core)
CM
mkdir -p include && touch src/core.cpp src/main.cpp
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
# the image has no jq, so read the JSON with a few lines of Python
python3 - <<'PY'
import json
entries = json.load(open("build/compile_commands.json"))
for e in entries:
    print(e["file"].split("/ed/")[1])
    print("    " + e["command"])
print("keys:", ", ".join(sorted(entries[0])))
PY
src/core.cpp
    /usr/bin/c++ -DCORE_API=1 -I/home/learner/ed/include -std=gnu++20 -fno-diagnostics-color -o CMakeFiles/core.dir/src/core.cpp.o -c /home/learner/ed/src/core.cpp
src/main.cpp
    /usr/bin/c++ -DCORE_API=1 -I/home/learner/ed/include -std=gnu++20 -fno-diagnostics-color -o CMakeFiles/app.dir/src/main.cpp.o -c /home/learner/ed/src/main.cpp
keys: command, directory, file, output

Each entry has the directory to run in, the file, the full command and the output. Tools look for the file in the project root or a build/ folder, so the usual trick is a symlink (ln -s build/compile_commands.json .) or telling the tool where it is (clangd --compile-commands-dir=build, clang-tidy -p build). Header files aren't listed; clangd infers their flags from a nearby source file.

You can also set "CMAKE_EXPORT_COMPILE_COMMANDS": "ON" in a preset, or the CMAKE_EXPORT_COMPILE_COMMANDS environment variable (3.17+) to turn it on for every project you configure.

The File API: what IDEs read

IDEs need more than compile commands: the list of targets, their types and output files, the source groups, the install rules, the cache. CMake provides it through the File API: a client drops a query file into <build>/.cmake/api/v1/query/, and on the next configure CMake writes JSON replies into .cmake/api/v1/reply/. CMake Tools, CLion, Visual Studio, Qt Creator and KDevelop all use it.

bash · try it yourself
mkdir -p ed && cd ed
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Ed LANGUAGES CXX)
add_library(core STATIC core.cpp)
add_executable(app main.cpp)
target_link_libraries(app PRIVATE core)
CM
touch core.cpp main.cpp
# Ask for the "codemodel" (targets) the way an IDE does: an empty query file.
mkdir -p build/.cmake/api/v1/query
touch build/.cmake/api/v1/query/codemodel-v2
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cd build/.cmake/api/v1/reply
ls | sed -E 's/-[0-9a-f]{20}\.json$/-<hash>.json/; s/[0-9T-]{17,}/<time>/' | sort
python3 - <<'PY'
import glob, json
model = json.load(open(glob.glob("codemodel-v2-*.json")[0]))
for t in model["configurations"][0]["targets"]:
    d = json.load(open(t["jsonFile"]))
    deps = [x["id"].split(":")[0] for x in d.get("dependencies", [])]
    print(f'{d["name"]}: {d["type"]}, artifacts {[a["path"] for a in d["artifacts"]]}, depends on {deps}')
PY
codemodel-v2-<hash>.json
directory-.-<hash>.json
index<time>.json
target-app-<hash>.json
target-core-<hash>.json
app: EXECUTABLE, artifacts ['app'], depends on ['core']
core: STATIC_LIBRARY, artifacts ['libcore.a'], depends on []

That is the model behind an IDE's target list: names, types, the files they produce, and the dependency graph. You won't write File API clients often, but knowing it exists explains why IDEs no longer need special "extra generators" (CodeBlocks, Eclipse), which CMake 4 marks as deprecated.

VS Code: the CMake Tools extension

Microsoft's CMake Tools extension (with the C/C++ extension or clangd for language support) drives configure, build, test and debug from the status bar and the command palette:

  • With a CMakePresets.json in the folder, it shows your configure, build and test presets: choose them in the CMake side bar, and everybody uses the same settings as CI.
  • Without presets, it uses kits (detected compilers) and variants (build types).
  • "CMake: Configure", "Build", "Run Tests" (CTest integration in the Test Explorer), "Debug" (launches the selected target under the debugger), and "CMake: Configure with CMake Debugger" (breakpoints inside CMakeLists.txt).

Useful workspace settings (.vscode/settings.json):

json
{
  "cmake.useCMakePresets": "always",
  "cmake.configureOnOpen": true,
  "cmake.buildDirectory": "${workspaceFolder}/build/${buildType}",
  "cmake.ctest.parallelJobs": 8,
  "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools",
  "clangd.arguments": ["--compile-commands-dir=${workspaceFolder}/build"]
}

Use either the Microsoft C/C++ IntelliSense (fed by CMake Tools as the configuration provider) or clangd (fed by compile_commands.json), not both at once.

CLion

JetBrains CLion treats CMake as its native project model:

  • Opening a folder with a CMakeLists.txt configures it; CMake profiles (Settings → Build, Execution, Deployment → CMake) correspond to build directories. CLion imports CMakePresets.json configure and build presets as profiles automatically.
  • Toolchains (local, WSL, Docker, remote host) pick the compiler, debugger and CMake used by a profile.
  • The CMake tool window shows the configure log; CMake debugger support lets you step through CMakeLists.txt; CTest tests appear as run configurations; compile_commands.json-only projects can be opened too.

Visual Studio and others

Visual Studio 2022 ("Open Folder" with a CMakeLists.txt) reads CMakePresets.json as well, and Qt Creator, KDevelop and Xcode (through the Xcode generator) round out the list. Because they all read the same presets, a project that keeps its settings in CMakePresets.json works the same in every IDE, on the command line and in CI.

Test yourself

What does CMAKE_EXPORT_COMPILE_COMMANDS ON produce?

  1. A Makefile
  2. build/compile_commands.json listing the full compile command of every source file
  3. A VS Code settings file
  4. A CDash report

How does an IDE ask CMake for the list of targets?

  1. It parses CMakeLists.txt
  2. Through the File API: a query file in .cmake/api/v1/query, answered with JSON in .cmake/api/v1/reply
  3. From CMakeCache.txt
  4. With --graphviz

Why keep build settings in CMakePresets.json when the team uses different IDEs?

  1. IDEs require it
  2. VS Code, CLion and Visual Studio all read the same presets, so everyone (and CI) configures identically
  3. It makes builds faster
  4. Presets replace CMakeLists.txt