In this recipe, we achieved the execution of CMake code at build time. For this, we defined a custom command:
add_custom_command(
OUTPUT
${CMAKE_CURRENT_BINARY_DIR}/generated/version.hpp
ALL
COMMAND
${CMAKE_COMMAND} -D TARGET_DIR=${CMAKE_CURRENT_BINARY_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/git-hash.cmake
WORKING_DIRECTORY
${CMAKE_CURRENT_SOURCE_DIR}
)
We also defined a custom target, as follows:
add_custom_target(
get_git_hash
ALL
DEPENDS
${CMAKE_CURRENT_BINARY_DIR}/generated/version.hpp
)
The custom command invokes CMake to execute the git-hash.cmake CMake script. This is achieved by using the -P CLI switch, to pass the location of the script. Notice that we can pass options with the -D CLI switch, as we usually would. The git-hash.cmake script generates ${TARGET_DIR}/generated/version.hpp. The custom target is added to the ALL target, and depends on the output of the custom command. In other words, when we build the default target, we make sure that the custom command is run. Also, observe that the custom command has the ALL target as output. With that, we make sure that version.hpp is generated every time.