TExcelTAD
Home › GNU Make & Ninja › Toolkit: compile_commands.json & Editors

Toolkit: compile_commands.json & Editors

An editor that understands C or C++ (go to definition, live errors, refactoring) has to compile each file in its head, and for that it needs the same flags the build uses: include paths, defines, the language standard. The standard way to hand them over is a compilation database, compile_commands.json, in the project root. clangd, clang-tidy, CLion, VS Code's C/C++ extension, Qt Creator, Vim and Emacs LSP clients all read it.

The format

A JSON array with one entry per compiled file:

json
[
  {
    "directory": "/home/ada/proj",
    "command": "gcc -Iinclude -DNDEBUG -O2 -c src/main.c -o build/main.o",
    "file": "src/main.c",
    "output": "build/main.o"
  }
]

arguments (a JSON list) may replace command; directory is where the command runs, and relative paths are resolved against it.

Getting one from each build system

Build How
Ninja (hand-written or generated) ninja -t compdb cc > compile_commands.json (name your compile rules)
CMake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON (Makefile and Ninja generators) writes it into the build directory
Meson always writes compile_commands.json into the build directory
Make not built in: use bear or compiledb

bear runs the real build and records every compiler invocation by intercepting process starts (LD_PRELOAD on Linux). It's exact, because it sees what really ran, but it needs a real (full) build. Put -- between bear's options and the build command:

bash · try it yourself
mkdir -p proj/src/net && cd proj
printf 'int tcp(void) { return 0; }\n' > src/net/tcp.c
printf 'int main(void) { return 0; }\n' > src/main.c
cat > Makefile <<'MK'
CFLAGS := -O2 -Wall
CPPFLAGS := -Isrc -DVERSION=3
OBJS := build/main.o build/net/tcp.o
build/app: $(OBJS)
	gcc $^ -o $@
build/%.o: src/%.c
	@mkdir -p $(@D)
	gcc $(CPPFLAGS) $(CFLAGS) -c 
lt; -o $@ MK bear -- make -j1 echo "--- compile_commands.json:" python3 -c 'import json; [print(e["file"], "->", e.get("output", "?"), "|", " ".join(e["arguments"][:4])) for e in json.load(open("compile_commands.json"))]'
gcc -Isrc -DVERSION=3 -O2 -Wall -c src/main.c -o build/main.o
gcc -Isrc -DVERSION=3 -O2 -Wall -c src/net/tcp.c -o build/net/tcp.o
gcc build/main.o build/net/tcp.o -o build/app
--- compile_commands.json:
/home/learner/proj/src/main.c -> /home/learner/proj/build/main.o | /usr/bin/gcc -Isrc -DVERSION=3 -O2
/home/learner/proj/src/net/tcp.c -> /home/learner/proj/build/net/tcp.o | /usr/bin/gcc -Isrc -DVERSION=3 -O2

The build ran normally, and bear wrote one entry per compile (the link line has no source file, so it is left out). It records what the kernel saw: the compiler's full path (/usr/bin/gcc) and absolute file/output paths. For a build spread over several commands, bear --append -- make -C tests adds to the existing file instead of replacing it.

compiledb (a Python tool, pip install compiledb) instead parses Make's output, so it can work from a dry run: compiledb make builds and parses, compiledb -n make only parses make -n and compiles nothing:

bash · try it yourself
mkdir -p proj/src/net && cd proj
printf 'int tcp(void) { return 0; }\n' > src/net/tcp.c
printf 'int main(void) { return 0; }\n' > src/main.c
cat > Makefile <<'MK'
CFLAGS := -O2 -Wall
CPPFLAGS := -Isrc -DVERSION=3
OBJS := build/main.o build/net/tcp.o
build/app: $(OBJS)
	gcc $^ -o $@
build/%.o: src/%.c
	@mkdir -p $(@D)
	gcc $(CPPFLAGS) $(CFLAGS) -c 
lt; -o $@ MK compiledb -n make ls build 2>/dev/null || echo "(nothing was built)" echo "--- compile_commands.json:" python3 -c 'import json; [print(e["file"], "->", e.get("output", "?"), "|", " ".join(e["arguments"][:4])) for e in json.load(open("compile_commands.json"))]'
(nothing was built)
--- compile_commands.json:
src/main.c -> ? | gcc -Isrc -DVERSION=3 -O2
src/net/tcp.c -> ? | gcc -Isrc -DVERSION=3 -O2

Same flags, no build: useful for a large project you just cloned. The entries keep the text Make printed (gcc, relative file paths resolved against directory, no output field), which clangd handles fine. The catch is that parsing text is a guess: a compiler started from inside a shell script or another tool never appears in Make's output, so compiledb misses it, while bear still sees it.

The idea behind compiledb fits in a few lines of Python: ask Make for every command (-nB = dry run, everything out of date) and keep the compiler lines:

bash · try it yourself
mkdir -p proj/src/net && cd proj
printf 'int tcp(void) { return 0; }\n' > src/net/tcp.c
printf 'int main(void) { return 0; }\n' > src/main.c
cat > Makefile <<'MK'
CFLAGS := -O2 -Wall
CPPFLAGS := -Isrc -DVERSION=3
OBJS := build/main.o build/net/tcp.o
build/app: $(OBJS)
	gcc $^ -o $@
build/%.o: src/%.c
	@mkdir -p $(@D)
	gcc $(CPPFLAGS) $(CFLAGS) -c 
lt; -o $@ MK cat > mkcompdb.py <<'PY' import json, os, shlex, subprocess, sys out = subprocess.run(["make", "-nB"], capture_output=True, text=True).stdout entries = [] for line in out.splitlines(): args = shlex.split(line) if args and args[0] in ("gcc", "cc", "clang") and "-c" in args: src = next(a for a in args if a.endswith(".c")) entries.append({"directory": os.getcwd(), "arguments": args, "file": src}) json.dump(entries, sys.stdout, indent=1) print() PY python3 mkcompdb.py > compile_commands.json python3 -c 'import json; [print(e["file"], " ".join(e["arguments"][1:4])) for e in json.load(open("compile_commands.json"))]' ls build 2>/dev/null || echo "(nothing was built)"
src/main.c -Isrc -DVERSION=3 -O2
src/net/tcp.c -Isrc -DVERSION=3 -O2
(nothing was built)

Real tools handle much more (cd dir && … lines, recursive make[1]: Entering directory messages, compiler wrappers like ccache gcc), but the principle is the same. Regenerate the database whenever flags or files change: a stale one gives you false "file not found" squiggles.

Tip: Generate the database into the build directory and symlink it into the source root (ln -s build/compile_commands.json .), or point clangd at it with CompilationDatabase: build in a .clangd file. Add compile_commands.json to .gitignore: it contains absolute paths.

Editor support for Makefiles and Ninja files

Editor Makefiles build.ninja
any EditorConfig-aware editor an .editorconfig section [{Makefile,*.mk}] with indent_style = tab [*.ninja] with indent_style = space
VS Code built-in highlighting; Microsoft's Makefile Tools extension (build/debug targets, feeds IntelliSense from make --dry-run) community "Ninja" syntax extensions
Vim / Neovim filetype=make sets noexpandtab automatically syntax file shipped in Ninja's misc/ninja.vim
Emacs makefile-mode (inserts real TABs, highlights space-indented recipes) ninja-mode.el in Ninja's misc/
CLion Makefile projects are supported directly (it analyses the build output); Ninja via CMake/Meson

A minimal .editorconfig that prevents the missing-separator error for everyone on the team:

ini
root = true

[*]
indent_style = space
indent_size = 4

[{Makefile,makefile,GNUmakefile,*.mk}]
indent_style = tab

And a check you can run in CI, which fails if any recipe-looking line is indented with spaces:

bash · try it yourself
mkdir -p lint && cd lint
printf 'app: main.o\n\tgcc $^ -o $@\nclean:\n    rm -f app\n' > Makefile
if grep -nE '^ {2,}[^ #]' Makefile; then echo "space-indented lines found"; else echo "ok"; fi
4:    rm -f app
space-indented lines found

(It also flags space-indented lines inside ifeq blocks, which are legal; tune the pattern to your style.)

Test yourself

Why do clangd and similar tools need compile_commands.json?

  1. To run the build
  2. To know the exact include paths, defines and flags each file is compiled with
  3. To format code
  4. To download headers

What is the difference between bear and compiledb?

  1. None
  2. bear intercepts the commands of a real build; compiledb parses Make's (possibly dry-run) output
  3. bear only works with Ninja
  4. compiledb needs root

Which .editorconfig setting prevents space-indented recipes?

  1. indent_size = 8 for all files
  2. indent_style = tab in a section for Makefiles
  3. end_of_line = lf
  4. charset = utf-8