3

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.

Kevin
  • 16,549
  • 8
  • 60
  • 74
Marius CH
  • 33
  • 4

1 Answers1

6

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()
Kevin
  • 16,549
  • 8
  • 60
  • 74
  • 2
    Excellent answer, thank you! If anyone knows why there isn't such a built-in CMake command for this use-case already available, it would be nice to learn. – Marius CH Nov 26 '19 at 15:28
  • 1
    @MariusCH: "why there isn't such a built-in CMake command for this use-case already available" - See that answer to the duplicate question: https://stackoverflow.com/a/53835855/3440745. – Tsyvarev Nov 26 '19 at 16:41
  • @Tsyvarev: thank you for the link and for marking this as a duplicate. – Marius CH Nov 27 '19 at 07:27