CMake add_custom_target() echo example
The COMMENT field of CMake’s
add_custom_target()
is intended to print messages during the build.
However, this field is a no-op when using
CMake Generators
like Ninja and GNU Make.
To reliably print messages during the build regardless of the Generator used,
create a custom echo command using CMake’s built-in cmake -E echo functionality.
Example CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(demo LANGUAGES NONE)
set(_out ${PROJECT_BINARY_DIR}/output.txt)
add_custom_target(touchtgt ALL
COMMAND ${CMAKE_COMMAND} -E touch ${_out}
COMMAND ${CMAKE_COMMAND} -E echo "Touch ${_out}"
)Demonstrate by
cmake -Bbuild
cmake --build buildBecause of the ALL parameter, the touchtgt target will be built by default when you run cmake --build build, and it will print the message “Touch <path_to_output.txt>” during the build process.
To make the file be touched only if it doesn’t exist, use a combination of add_custom_command() and add_custom_target() instead:
cmake_minimum_required(VERSION 3.10)
project(demo LANGUAGES NONE)
set(_out ${PROJECT_BINARY_DIR}/output.txt)
add_custom_command(
OUTPUT ${_out}
COMMAND ${CMAKE_COMMAND} -E touch ${_out}
COMMAND ${CMAKE_COMMAND} -E echo "Touch ${_out}"
)
add_custom_target(touchtgt ALL
DEPENDS ${_out}
)