Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy contents of a directory into build directory after make with CMake?

Tags:

c++

cmake

I've got some config files (xml, ini, ...) in the config directory next to the source files. How can I copy all the files in the config directory into the build directory (next to the executable file) each time I make the project?

like image 494
B Faley Avatar asked Nov 17 '12 10:11

B Faley


People also ask

What does CMake -- build do?

CMake is a cross-platform build system generator. Projects specify their build process with platform-independent CMake listfiles included in each directory of a source tree with the name CMakeLists. txt. Users build a project by using CMake to generate a build system for a native tool on their platform.

What files does CMake generate?

When you create a new CMake project in CLion, a CMakeLists. txt file is automatically generated under the project root.


3 Answers

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.
like image 117
Fraser Avatar answered Oct 19 '22 10:10

Fraser


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)
like image 21
hyrchao Avatar answered Oct 19 '22 09:10

hyrchao


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

like image 5
rajneesh Avatar answered Oct 19 '22 10:10

rajneesh