Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying assets directory from source to build directory in CMake

Tags:

c++

cmake

assets

I am trying to write a game for practice in C++. I am using CMake for this, and my project gets built in a separate build directory automatically by my IDE. However, my assets folder is not being copied over to the new directory.

Currently, I am attempting to resolve this with the following:

add_custom_command(TARGET ${PROJECT_NAME}
    POST_BUILD
    COMMAND cp -r ${PROJECT_SOURCE_DIR}/assets ${CMAKE_BINARY_DIR}
    )

However, this seems to have absolutely no effect on the outcome and the assets directory is still not present in my build directory.

How can I actually make it copy this asset directory to my build location? Is there a smarter way to point my program to my assets location (perhaps one that will also work with assets in /usr/share?)

like image 837
Ethan McTague Avatar asked Feb 27 '17 02:02

Ethan McTague


People also ask

What is build in CMake?

CMake can generate a native build environment that will compile source code, create libraries, generate wrappers and build executables in arbitrary combinations. CMake supports in-place and out-of-place builds, and can therefore support multiple builds from a single source tree.


2 Answers

Two ways I've found, both ensuring that it copies on target build and stays up to date even if the target doesn't need to re-build.


The first uses the CMake command line tool copy_directory. It's unclear from the documentation whether this copy always happens, regardless if files in the assets directory were updated or not, or if it only copies when the asset files don't exist or an asset file was updated:

add_custom_target(copy_assets
    COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_LIST_DIR}/assets ${CMAKE_CURRENT_BINARY_DIR}/assets
)
add_dependencies(mytarget copy_assets)

The second requires a small additional CMake script file, but it allows us to use the file(COPY ...) CMake comamnd, which states in the documentation that "copying preserves input file timestamps, and optimizes out a file if it exists at the destination with the same timestamp."

First, create the CMake script file copy-assets.cmake in the same directory as your CMakeLists.txt, with the contents being (similar to Ethan McTague's answer)

file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets DESTINATION ${CMAKE_CURRENT_BINARY_DIR})

And then in your CMakeLists.txt, add the following:

add_custom_target(copy_assets
    COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_LIST_DIR}/copy-resources.cmake
)
add_dependencies(mytarget copy_assets)
like image 191
tdashroy Avatar answered Sep 21 '22 00:09

tdashroy


After quite a while of more searching, I managed to find the file(COPY {files} DESTINATION {directory}) command:

file(COPY assets DESTINATION ${CMAKE_BINARY_DIR})
like image 27
Ethan McTague Avatar answered Sep 20 '22 00:09

Ethan McTague