How to use CMAKE_EXPORT_COMPILE_COMMANDS?

2019-01-14 17:41发布

问题:

I've been trying to use clang-modernize with CMAKE_EXPORT_COMPILE_COMMANDS as recommended in the help of this tool.

With this option cmake generates a JSON file containing compile info like include paths (see also).

This variable is accepted on the command line of cmake, but cmake --help-variable CMAKE_EXPORT_COMPILE_COMMANDS doesn't work (which is coherent with this mailing list posting).

Has someone any idea on how to use it?

I could also use it with cppcheck.

Some more info

I've discovered on a clang developer forum that this cmake feature is not available on all generators. This might change in the future, in the mean time my question remains and I will try too see what happen if I use other generators than Visual Studio.

回答1:

I suggest setting

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

in the CMakeList.txt



回答2:

As of CMake 3.5 the CMAKE_EXPORT_COMPILE_COMMANDS option is supported by the Ninja and Makefiles generators.

That means to generate a JSON compile database one has to select a generator that supports it.

For example on UNIX just:

cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 /path/to/src

(as it uses the makefile generator there, by default)

Otherwise you can explicitly specify a generator like this:

cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 /path/to/src -G Ninja

Or:

cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 /path/to/src -G 'Unix Makefiles'

Or another makefiles variant that your cmake supports - a list of supported generators is included in the output of cmake --help.

Note that the compile database JSON file is generated at cmake execution time - not at compile time. Also, with recent clang versions (e.g. clang >= 3.8), clang-modernize was merged into clang-tidy.



回答3:

I too was not able to get to work on the Visual Studio generator. It did, however, work using the "NMake Makefiles" generator.

C:\work\build>cmake -G "NMake Makefiles"  -DCMAKE_EXPORT_COMPILE_COMMANDS=ON  ..