use CMAKE to copy compile_commands.json to project root

Viewed 490

This is the content I have in my CMakeLists.txt file that is located in my project root:

cmake_minimum_required(VERSION 3.13)
project(cmake_wrapper)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_custom_target(
    copy-compile-commands ALL
    ${CMAKE_COMMAND} -E copy_if_different
    ${CMAKE_BINARY_DIR}/compile_commands.json
    ${CMAKE_CURRENT_LIST_DIR}
    )

# I am using conan & everything works fine, so you may ignore 2 lines below
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup() 

# add submodule
add_subdirectory(src)

Then I run cmake .. in my build folder, and I got the compile_commands.json generated in build folder but I didn't see the file been copied into my project root.

UPDATE: So seems I need to run build/make to trigger this step. Is there a way to copy the file before run make but right after the compile_commands.json been generated?

2 Answers

So seems I need to run build/make to trigger this step. Is there a way to copy the file before run make but right after the compile_commands.json been generated?

No. CMake generates the compile_commands.json during the generation step which happens immediately after your CMake code runs (configure step) and before the generated build system runs (build step).

CMake has no features to execute arbitrary CMake code during generation.

Instead of copying, create a symlink. At configure stage.

execute_process(
    COMMAND ${CMAKE_COMMAND} -E create_symlink
        ${CMAKE_BINARY_DIR}/compile_commands.json
        ${CMAKE_SOURCE_DIR}/compile_commands.json
)
Related