首页 > 解决方案 > cmake 2.8 自定义目标复制多个文件

问题描述

我不得不在 Linux 环境中使用较旧的 cmake 版本 2.8.12。

作为预构建步骤,我必须将多个头文件从源目录复制到目标目录。我决定使用add_custom_target从句。如果这本身就是个坏主意,请告诉我。例如:

add_custom_target( prebuild
  COMMENT "Prebuild step: copy other headers"
  COMMAND ${CMAKE_COMMAND} -E copy_if_different  ${CMAKE_SOURCE_DIR}/../other/include/alpha.h  ${CMAKE_SOURCE_DIR}/include/other
  COMMAND ${CMAKE_COMMAND} -E copy_if_different  ${CMAKE_SOURCE_DIR}/../other/include/bravo.h  ${CMAKE_SOURCE_DIR}/include/other
  COMMAND ${CMAKE_COMMAND} -E copy_if_different  ${CMAKE_SOURCE_DIR}/../other/include/charlie.h  ${CMAKE_SOURCE_DIR}/include/other
)

add_executable( myapp main.cxx )

# My application depends on the pre-build step.
add_dependencies( myapp prebuild )

set_target_properties( myapp PROPERTIES COMPILE_FLAGS "-g" )
install( TARGETS myapp DESTINATION ${BIN_INSTALL_DIR} )

列出每个头文件会很乏味。我知道如何搜索所有头文件并将它们放入列表变量中。例如。

file( GLOB other_headers "${CMAKE_SOURCE_DIR}/../other/include/*.h" )

但是,如何将该列表变量放在add_custom_target子句中使用?

有没有办法在add_custom_target子句中复制多个文件?

有没有更好的方法来复制多个文件作为构建我的应用程序的依赖项的预构建步骤?

受限于旧版本的 cmake 限制了我的选择。以下是我尝试过但没有成功的事情。

标签: linuxcmakeprebuild

解决方案


在子句中使用foreach循环add_custom_target不起作用。

但是使用foreach您可以创建一个包含所有必需命令的变量。然后在 add_custom_target 中使用该变量:

set(commands)

# Assume 'other_headers' contain list of files
foreach(header ${other_headers})
  list(APPEND commands
    COMMAND ${CMAKE_COMMAND} -E copy_if_different ${header}  ${CMAKE_SOURCE_DIR}/include/other)
endforeach()

add_custom_target( prebuild
  COMMENT "Prebuild step: copy other headers"
  ${commands}
)

推荐阅读