How to turn makefile into JSON Compilation Database?
Say we have make
files (not cmake/premake/ninja etc) for our project that do work for gcc and clang. We want to generate out from them JSON Compilation Database to feed it into clang-modernize
tool. How to do such thing? (is there any parser in clang infrastructure or some script with usage like make CC='cc_args.py gcc' CXX='cc_args.py g++'
or some other tool)?
I have no personal experience with it but Bear seems to be targeted to your scenario. (It was linked from the clang-modernize site.)
Make has a usually-undesired feature of emitting the compiler command lines to its standard output, but in this case you can use it with a shell (and jq) pipeline. With GNU Make on Bash:
make --always-make --dry-run \
| grep -wE 'gcc|g\+\+' \
| grep -w '\-c' \
| jq -nR '[inputs|{directory:".", command:., file: match(" [^ ]+$").string[1:]}]' \
> compile_commands.json
On Windows, cmd.exe
syntax is similar:
- use
^
instead of\
for line continuation - use
"
-delimited strings only - use
"""
to escape a"
within a"
-delimited string - use
^^
to escape a^
within a"
-delimited string
However, this doesn't handle cases where the makefile recursively invokes itself (or other makefiles) in subdirectories using the -C
argument.
Maybe someone is in my same situation. I have a macOS and Bear was generating an empty compile_commands.json
file. They acknowledge this problem in the README and suggest to use scan-build as a workaround. Unfortunately, I was still getting an empty file. Two alternative solutions I found are:
- compiledb, which worked in my case.
- a combination of clang++ compiler's
-MJ
option plus sed, detailed here, that seems simple enough and easy to transform into amake
target. This one I have not tested.