我被迫在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限制了我的选择。以下是我尝试未成功的事情。
copy_if_different
命令可以采用多个源路径。COMMAND_EXPAND_LISTS
添加到add_custom_target
子句无效。只有在更新的cmake版本中,该功能才可用。foreach
子句中使用add_custom_target
循环不起作用。在我看到的其他示例中,它们始终使用foreach
循环,而add_custom_target
在该循环内。但是,如果我这样做了,那么我将不知道如何将其作为应用程序构建的依赖项。在
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}
)
您可以使用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()