Getting a cmake executable path to run it on a cus

2019-03-05 14:54发布

问题:

I am creating an executable using the add_executable(foo sources.cpp) then I would like to have a target that runs foo, so right now I'm doing this:

add_custom_target(run_foo 
   COMMAND ${CMAKE_BINARY_DIR}/test/foo 
   DEPENDS foo 
   WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)

it works now, but I feel like I'm doing it wrong by hardcoding the path to the binary in "COMMAND". Isn't there a way to get the path to the binary from foo ?

回答1:

add_custom_target(COMMAND $<TARGET_FILE:foo> ...)

See:

http://www.cmake.org/cmake/help/v3.0/manual/cmake-generator-expressions.7.html



回答2:

In fact, you don't even need a generator expression :) At least /w modern CMake:

If COMMAND specifies an executable target name (created by the add_executable() command) it will automatically be replaced by the location of the executable created at build time.

add_executable(foo ...)
add_custom_target(COMMAND foo ...)


标签: c++ cmake