cmake 2.8自定义目标复制多个文件

cmake 2.8 custom target to copy multiple files

我不得不在 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 限制了我的选择。以下是我尝试过但没有成功的事情。

Using a foreach loop within the add_custom_target clause does not work.

但是使用 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}
)

您可以使用 foreach 为每个头文件添加自定义目标,但也可以将 add_dependencies() 调用拉入循环块:

add_executable( myapp main.cxx )

foreach(cur_header ${other_headers})
  # Get the filename from the full path.
  get_filename_component(my_header_name ${cur_header} NAME)
  # Add a new custom target for the current header.
  add_custom_target( prebuild_${my_header_name}
    COMMENT "Prebuild step: copy other headers"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different ${cur_header} ${CMAKE_SOURCE_DIR}/include/other
  )
  # My application depends on the each pre-build target.
  add_dependencies( myapp prebuild_${my_header_name} )
endforeach()