在使用 CMake 进行 make 之后,如何将目录的内容复制到生成目录中?

在源文件旁边的 config目录中有一些配置文件(xml、 ini、 ...)。如何在每次制作项目时将配置目录中的所有文件复制到构建目录(可执行文件旁边) ?

92283 次浏览

CMake supports a shell type file copy. This link should be helpful for you - How to copy directory from source tree to binary tree?

In my project i use INSTALL to specify in CMake, what and where i move my binary with conf file. After execution of cmake, use "make install".

You can use add_custom_command.

Say your target is called MyTarget, then you can do this:

add_custom_command(TARGET MyTarget PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_SOURCE_DIR}/config/ $<TARGET_FILE_DIR:MyTarget>)

This executes every time you build MyTarget and copies the contents of "/config" into the directory where the target exe/lib will end up.

As Mark Lakata points out in a comment below, replacing PRE_BUILD with POST_BUILD in the add_custom_command ensures that copying will only happen if the build succeeds.

Explanation

  • ${CMAKE_COMMAND} is the path to CMake
  • -E makes CMake run commands instead of building
  • copy_directory is a Command-Line Tool
  • config is the directory (that falls under the root of the project) who's contents will be copied into the build target
  • $<TARGET_FILE_DIR:MyTarget> is a generator expression, described in the add_custom_command documentation.

In addition to the top answer,

To copy the directory itself instead of the contents, you can add /${FOLDER_NAME} to the end of the second parameter.

Like this:

add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_SOURCE_DIR}/config $<TARGET_FILE_DIR:${PROJECT_NAME}>/config)

Use symbolic links


CMake enables symbolic links via create_symlink:

add_custom_command(TARGET ${CMAKE_PROJECT_NAME} PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E create_symlink
${CMAKE_SOURCE_DIR}/config $<TARGET_FILE_DIR:${PROJECT_NAME}>/config)

It ensures that when you make a change to the files in the directory, build folder would subsequently be updated.