Issue
CMake's add_custom_command()
allows one to run a command (through the COMMAND
option) before or after building the target (using PRE_BUILD
, PRE_LINK
and POST_BUILD
). The command can be an executable or external "script", but not a CMake macro/function.
Is there a similar command like add_custom_command()
, which instead allows passing of a CMake function/macro and schedule it before/after a target was built?
If not, what options are there, besides implementing the COMMAND
as a re-run of CMake with a flag that enables the functionality inside the function/macro?
[EDIT] The function/macro will take as input the CMake target name and a target specific directory path.
Solution
The command can be a CMake macro or function. You just have to encapsulate it in a CMake file. CMake's add_custom_command()
supports running further CMake code as a script, with the -P
option. You can pass arguments to the function using the -D
option as well. For this example, we will pass two arguments, TARGET_NAME
and TARGET_PATH
:
# Define the executable target.
add_executable(MyExecutable ${MY_SRCS})
add_custom_command(TARGET MyExecutable
POST_BUILD
COMMAND ${CMAKE_COMMAND}
-DTARGET_NAME=MyExecutable
-DTARGET_PATH=${CMAKE_CURRENT_SOURCE_DIR}
-P ${CMAKE_SOURCE_DIR}/my_script.cmake
COMMENT "Running script..."
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
The my_script.cmake
file can include one or more pre-defined CMake functions, then call those functions, with something like this:
include(my_function.cmake)
# Call the function, passing the arguments we defined in add_custom_command.
my_function(${TARGET_NAME} ${TARGET_PATH})
For completeness, the CMake function my_function
could look like this:
# My CMake function.
function(my_function target_name target_path)
message("Target name: ${target_name}")
message("Target directory: ${target_path}")
endfunction()
Answered By - Kevin