David Pikas
David Pikas

Reputation: 21

Generating compile_commands.json without generating build files

I'd like to generate a compile_commands.json file for use with the clangd language server. However, EXPORT_COMPILE_COMMANDS only works for the make and ninja build systems. When building a project that uses a different build system it would be convenient to also be able to generate compile_commands.json files as if I was using make or ninja without actually generating any build files that interfere with the build system that I'm using to perform the build.

What is the most convenient way to do this with cmake?

Upvotes: 0

Views: 2149

Answers (2)

Roland Sarrazin
Roland Sarrazin

Reputation: 1345

My use case was to generate compile_commands.json for use with clang-tidy on Windows that has neither any GNU-like toolchain installed nor any make program.

Taking inspiration from this answer in Can I skip cmake compiler tests or avoid "error: unrecognized option '-rdynamic'", I managed to do so with the following command: cmake.exe .. -G"MinGW Makefiles" -DCMAKE_MAKE_PROGRAM=rundll32 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_C_COMPILER=rundll32 -DCMAKE_CXX_COMPILER=rundll32

Note that rundll32 can be replaced by anything of your choice (it'll be used as compiler in the created compile_commands.json), but it needs to be callable (hence my choice of rundll32 which does nothing without parameter on Windows).

For your reference what is generated with a simple CMakeLists.txt:

cmake_minimum_required(VERSION 3.23)
project(test)

add_executable(test main.cpp)

and the resulting compile_commands.json:

[
{
  "directory": "C:/test/build",
  "command": "C:\\Windows\\System32\\rundll32.exe  -I\\c\\tmp  -o CMakeFiles\\test.dir\\main.cpp.obj -c C:\\test\\main.cpp",
  "file": "C:/test/main.cpp",
  "output": "CMakeFiles/test.dir/main.cpp.obj"
}
]

Upvotes: 2

Amir
Amir

Reputation: 1179

I think your only option here is to have a different build folder with Ninja or Makefile to generates the compile_commands.json and have a different build folder for your "actual" build.

The thing is, CMake is a generator, and it doesn't support mixed builds; and in fact, it should not. If they do that, you will end up having random artifacts from different build systems inside the build folder that might eventually conflicts with each others.

That being said, you are aware that what you get in Ninja-based compile_commands.json is not going to be fully relevant to your "actual" build system that you want to use. I can see it being useful, but not the same for sure.

Upvotes: 1

Related Questions