Indiana Kernick
Indiana Kernick

Reputation: 5341

How can I get the directory that contains the executable in CMake?

Depending on the generator used, CMAKE_CURRENT_BINARY_DIR may or may not contain the executable. Using the Unix Makefiles generator, the executable is placed directly into this directory. However, using the Xcode generator, the executable is placed in a subdirectory (Debug or Release).

I'm trying to copy some files into directory next to the executable. This is what I'm doing but it only works when I use make. Maybe there's a better way?

add_custom_command(
    TARGET Game POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_directory
        ${CMAKE_CURRENT_SOURCE_DIR}/assets
        ${CMAKE_CURRENT_BINARY_DIR}/assets
)

I found CMAKE_RUNTIME_OUTPUT_DIRECTORY_<CONFIG> but it doesn't seem to set. I tried CMAKE_RUNTIME_OUTPUT_DIRECTORY, CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG and the target properties RUNTIME_OUTPUT_DIRECTORY, RUNTIME_OUTPUT_DIRECTORY_DEBUG but they aren't set. Maybe this isn't what I'm looking for.

Upvotes: 2

Views: 707

Answers (1)

J-Christophe
J-Christophe

Reputation: 2070

To specify the target directory associated with an executable target named name_of_executable_target, consider using the $<TARGET_FILE_DIR:name_of_executable_target> generator expression.

add_custom_command(
    TARGET Game POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E make_directory
        $<TARGET_FILE_DIR:name_of_executable_target>/assets
    COMMAND ${CMAKE_COMMAND} -E copy_directory
        ${CMAKE_CURRENT_SOURCE_DIR}/assets
        $<TARGET_FILE_DIR:name_of_executable_target>/assets
    )

For more details, see https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html

Upvotes: 3

Related Questions