CMAKE即使源文件没有变化,也强制在后期构建中复制指定文件

时间:2018-01-26 19:24:19

标签: cmake

我的项目布局如下:

CMakeLists.txt
|
|--------subdir1
|          |--CMakeLists.txt
|          |--sourcefiles
|          |--filetocopy1
|
|--------subdir2
           |--CMakeLists.txt
           |--sourcefiles
           |--filetocopy2 

我想将filetocopy1和filetocopy2复制到build文件夹中的指定输出目录。所以在两者中,我都有类似

的东西
add_custom_command(                                                                                                                                                       
  TARGET nameoftargetinsubdir1                                                                                                                                             
  POST_BUILD                                                                                                                                                              
  COMMAND ${CMAKE_COMMAND} -E copy                                                                                                                                        
  "${CMAKE_CURRENT_SOURCE_DIR}/filetocopy1"                                                                                                    
  "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}"                                                                                                                                     
  )

问题是如果filetocopy1或filetocopy2发生更改,但源文件没有更改,则在build文件夹中调用make不会复制文件。有没有办法强迫它复制这些文件?我感觉我可能不得不将复制命令放在顶级CMakeLists.txt文件中。

2 个答案:

答案 0 :(得分:1)

重建目标可执行文件/库时,正在运行 POST_BUILD 自定义命令的主要目的。如果您不需要此类行为,请使用带有 OUTPUT DEPENDS 选项的常用自定义命令,并结合add_custom_target

# If someone needs file "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/filetocopy1",
# this command will create it if the file doesn't exist or is older than
# "${CMAKE_CURRENT_SOURCE_DIR}/filetocopy1".
add_custom_command(
  OUTPUT "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/filetocopy1"
  COMMAND ${CMAKE_COMMAND} -E copy
  "${CMAKE_CURRENT_SOURCE_DIR}/filetocopy1"
  "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}"
  DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/filetocopy1"
  )

# Custom target for activate the custom command above
add_custom_target(copy_file1 DEPENDS "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/filetocopy1")

# Whenever target 'nameoftargetinsubdir1' is requested, the custom target will be evaluated.
add_dependencies(nameoftargetinsubdir1 copy_file1)

答案 1 :(得分:0)

如果您只是想将这些文件复制到其他地方,我建议使用以下命令:

configure_file(${CMAKE_CURRENT_SOURCE_DIR}/filetocopy1 ${CMAKE_BINARY_DIR}/ COPYONLY) 

https://cmake.org/cmake/help/v3.10/command/configure_file.html

此命令简单有效。每当调用cmake时,它都会将文件复制到目标。