CMake:如何拥有复制文件的目标 [英] CMake: How to have a target for copying files

查看:29
本文介绍了CMake:如何拥有复制文件的目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下命令在每次编译后将配置文件复制到构建目录中.

I am using the following command to copy config files into the build directory after each compile.

# Gather list of all .xml and .conf files in "/config"
file(GLOB ConfigFiles ${CMAKE_SOURCE_DIR}/config/*.xml
                      ${CMAKE_SOURCE_DIR}/config/*.conf)

foreach(ConfigFile ${ConfigFiles})
  add_custom_command(TARGET MyTarget PRE_BUILD
                     COMMAND ${CMAKE_COMMAND} -E
                         copy ${ConfigFile} $<TARGET_FILE_DIR:MyTarget>)
endforeach()

每次编译项目都会触发这个动作.是否可以在 CMakeLists.txt 中创建一个目标来复制文件而无需编译任何东西?类似于制作副本".

This action is triggered every time I compile the project. Is it possible to create a target in CMakeLists.txt to copy files without needing to compile anything? Something like "make copy".

推荐答案

您应该能够添加一个名为 copy 的新自定义目标,并使其成为自定义命令的目标:

You should be able to add a new custom target called copy and make that the target of your custom commands:

file(GLOB ConfigFiles ${CMAKE_SOURCE_DIR}/config/*.xml
                      ${CMAKE_SOURCE_DIR}/config/*.conf)

add_custom_target(copy)
foreach(ConfigFile ${ConfigFiles})
  add_custom_command(TARGET copy PRE_BUILD
                     COMMAND ${CMAKE_COMMAND} -E
                         copy ${ConfigFile} $<TARGET_FILE_DIR:MyTarget>)
endforeach()

现在自定义命令只会在你构建 copy 时执行.

Now the custom commands will only execute if you build copy.

如果您想将此 copy 目标保留为 MyTarget 的依赖项,以便您可以仅复制文件或在构建 MyTarget 时复制它们,你需要打破循环依赖.(MyTarget依赖于copy,但是copy依赖于MyTarget来获取copy-to目录的位置).

If you want to keep this copy target as a dependency of MyTarget so that you can either just copy the files or have them copied if you build MyTarget, you'll need to break the cyclic dependency. (MyTarget depends on copy, but copy depends on MyTarget to get the location of the copy-to directory).

为此,您可以采用获取目标输出目录的老式方法:

To do this, you can resort to the old-fashioned way of getting a target's output directory:

add_custom_target(copy)
get_target_property(MyTargetLocation MyTarget LOCATION)
get_filename_component(MyTargetDir ${MyTargetLocation} PATH)
foreach(ConfigFile ${ConfigFiles})
  add_custom_command(TARGET copy PRE_BUILD
                     COMMAND ${CMAKE_COMMAND} -E
                         copy ${ConfigFile} ${MyTargetDir})
endforeach()
add_dependencies(MyTarget copy)

这篇关于CMake:如何拥有复制文件的目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆