Syntactic Fructose
Syntactic Fructose

Reputation: 20076

Strip path off of variable in CMake

Is there is way I can strip the path off of a variable in my CMakeLists.txt? Say I have a variable

RUNTIME_DEPENDENCIES = {
    src/frontend/solve.py
    src/frontend/other.py
}

these runtime dependencies are copied over to the bin for the executable to use during execution, but with the way I'm copying them they appear inside their respective folders. So my build folder looks like

    build
      | \
     src executable
      |
   frontend
   /       \
other.py  solve.py

i'd like the folder to simply contain

           build
    /       /         \
executable  other.py  solve.py

here's the actualy copy command used:

#copy runtime deps
add_custom_target(copy_runtime_dependencies ALL)
foreach(RUNTIME_DEPENDENCY ${RUNTIME_DEPENDENCIES})
    add_custom_command(TARGET copy_runtime_dependencies POST_BUILD
                       COMMAND ${CMAKE_COMMAND} -E copy
                       ${CMAKE_SOURCE_DIR}/${RUNTIME_DEPENDENCY}
                       $<TARGET_FILE_DIR:${EXECUTABLE_NAME}>/${RUNTIME_DEPENDENCY})
endforeach()

I realize I could simply change the 5th line above to

${CMAKE_SOURCE_DIR}/src/frontend/${RUNTIME_DEPENDENCY}

but in the case I have multiple dependencies outside of the src/frontend I don't want to have to write multiple seperate copy statements in my CMakeLists.txt

Upvotes: 6

Views: 13538

Answers (3)

Kevin
Kevin

Reputation: 18243

As of CMake 3.20, you can use the new cmake_path command for path manipulation in order to grab the FILENAME component of each path:

cmake_path(GET <path-var> FILENAME <out-var>)

For your example, you could do:

cmake_path(GET RUNTIME_DEPENDENCY FILENAME MY_FILE_NAME)

This command supersedes the get_filename_component command.

Upvotes: 2

Peter
Peter

Reputation: 14927

The function get_filename_component does this:

get_filename_component(barename ${RUNTIME_DEPENDENCY} NAME)

barename is the output variable to hold the filename with path removed. For example:

get_filename_component(barename "src/frontend/solve.py" NAME)
message(STATUS ${barename})

would print solve.py

Upvotes: 21

steveire
steveire

Reputation: 11074

$<TARGET_FILE_DIR:${EXECUTABLE_NAME}>/../

Upvotes: 0

Related Questions