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

问题描述 投票:1回答:2

我被迫在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限制了我的选择。以下是我尝试未成功的事情。

  • 如果我的cmake版本为3.5,则copy_if_different命令可以采用多个源路径。
  • COMMAND_EXPAND_LISTS添加到add_custom_target子句无效。只有在更新的cmake版本中,该功能才可用。
  • foreach子句中使用add_custom_target循环不起作用。在我看到的其他示例中,它们始终使用foreach循环,而add_custom_target在该循环内。但是,如果我这样做了,那么我将不知道如何将其作为应用程序构建的依赖项。
linux cmake prebuild
2个回答
1
投票

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}
)

0
投票

您可以使用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()
© www.soinside.com 2019 - 2024. All rights reserved.