我在项目的根目录中有一个CMakeLists.txt
,并且已打开CMAKE_EXPORT_COMPILE_COMMANDS
。
我正在文件夹内建立目标,并通过add_subdirectory
进行调用。该文件夹有自己的CMakeLists.txt
文件。
compile_commands.json
内置于二进制目录的根目录中,我想在运行cmake命令后将其复制到源目录的根目录中。
我尝试了两种方法。
add_custom_target
和add_custom_command
。
我创建了一个虚拟目标。我将此目标用于add_custom_command
来复制文件,但是它不会触发add_custom_command
中的命令。
file(COPY ...)
第一次触发命令时,compile_commands.json
不是通过cmake创建的。我不想运行cmake命令两次以将副本compile_commands.json
复制到源文件夹的根目录。
CMAKE_MINIMUM_REQUIRED(VERSION 3.8)
project(exec LANGUAGES CXX)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_subdirectory("DirectoyWithTarget")
add_custom_target(copy_compile_commands
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/compile_commands.json)
add_custom_command(
TARGET copy_compile_commands
PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_CURRENT_BINARY_DIR}/compile_commands.json
${CMAKE_CURRENT_SOURCE_DIR}/compile_commands.json
)
compile_commands.json
文件未复制到${CMAKE_CURRENT_SOURCE_DIR}
。这意味着add_custom_command
没有被触发。
答案 0 :(得分:4)
还没有进行太多测试,但这是我提出的两个基于cmake的解决方案。
代码少,但始终运行。
add_custom_target(
copy-compile-commands ALL
${CMAKE_COMMAND} -E copy_if_different
${CMAKE_BINARY_DIR}/compile_commands.json
${CMAKE_CURRENT_LIST_DIR}
)
更多代码,但是设置了依赖性,因此除非需要,否则不会运行。可以处理在二进制目录中删除compile_commands.json的情况。
# Copy to source directory
add_custom_target(
copy-compile-commands ALL
DEPENDS
${CMAKE_CURRENT_LIST_DIR}/compile_commands.json
)
add_custom_command(
OUTPUT ${CMAKE_CURRENT_LIST_DIR}/compile_commands.json
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_BINARY_DIR}/compile_commands.json
${CMAKE_CURRENT_LIST_DIR}/compile_commands.json
DEPENDS
# Unlike "proper" targets like executables and libraries,
# custom command / target pairs will not set up source
# file dependencies, so we need to list file explicitly here
generate-compile-commands
${CMAKE_BINARY_DIR}/compile_commands.json
)
# Generate the compilation commands. Necessary so cmake knows where it came
# from and if for some reason you delete it.
add_custom_target(generate-compile-commands
DEPENDS
${CMAKE_BINARY_DIR}/compile_commands.json
)
add_custom_command(
OUTPUT ${CMAKE_BINARY_DIR}/compile_commands.json
COMMAND ${CMAKE_COMMAND} -B${CMAKE_BINARY_DIR} -S${CMAKE_SOURCE_DIR}
)