custom_commands 

Send to Kindle
home » snippets » cmake » custom_commands



From: CustomCommandCustomTargetInstall

Most real world builds do not only build binaries and libraries, but also various other files, e.g. documentation, translations, etc. Furthermore, complex builds may build intermediate source files or build tools. CMake handles all this using the add_custom_*() commands. Here is a toy model for experimentation:

cmake_minimum_required(VERSION 2.6)

project(test)

add_custom_command(
    OUTPUT bla.txt 
    COMMAND cmake -E touch bla.txt
    )

add_custom_target(
    bla ALL 
    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/bla.txt)

install(
    FILES ${CMAKE_CURRENT_BINARY_DIR}/bla.txt
    DESTINATION usr/share/test)

add_custom_command() will create the file bla.txt in the build directory, if and only if, there is a target, which depends on it. add_custom_target() creates such a target. Note that the build dir '${CMAKE_CURRENT_BINARY_DIR}' has to be specified explicitly, since otherwise the dependence would be resolved inside the source tree. In this toy model no such source exists and CMake would fail.

So 'make bla' will create the file, but we added the target to the default target as well, by specifying 'ALL'. This in turn is required by the install() rule. install(FILES ...) is used to copy files somewhere for installation, but install() does not produce a proper dependence. Had we omitted 'ALL' in the target, CMake would run nicely, but 'make && make install' would fail, because bla.txt would not be generated. 'make bla && make install' on the other hand would work!