Search code examples
cmake

cmake - How to change compile_commands.json output location


Here's an example C++ project structure:

- {root}
    - CMakeLists.txt
    - build/
        - compile_commands.json  <-- This file gets generated  
    - src/
        - CMakeLists.txt
        - files here
    - compile_commands.json  <-- This is where I want compile_commands.json to be built to

If I build the project, it creates a "compile_commands.json" file in the "build" folder. But I actually want it underneath "{root}". Is there a way to specify the location of compile_commands.json? Or do I have to just copy it manually?

These are the command(s) that I typically use to build a project

(If cd'ed into {root}) cmake . -B build alternative: cd {root}/build && cmake ..

In both cases, compile_commands.json is added to the build folder


Solution

  • Is there a way to specify the location of compile_commands.json?

    There is no way. I believe the path for compile_commands.json generated when CMAKE_EXPORT_COMPILE_COMMANDS is set is hardcoded to be inside CMAKE_BINARY_DIR.

    Just create a symlink compile_commands.json -> ./build/compile_commands.json.

    Sometimes I add a symlink creation to CMakeLists.txt like so:

    if (PROJECT_IS_TOP_LEVEL AND UNIX)
        # Create symlink to compile_commands.json for IDE to pick it up
        execute_process(
            COMMAND ${CMAKE_COMMAND} -E create_symlink
                ${CMAKE_BINARY_DIR}/compile_commands.json
                ${CMAKE_CURRENT_SOURCE_DIR}/compile_commands.json
        )
    endif()