cmakecmake-custom-command

How to force a target to be rebuilt if a dependent script is updated?


I am written some custom scripts that are invoked in custom commands for CMake targets. I want the targets to be rebuilt if any of the scripts are updated (e.g. touch script.sh). I have tried several variations using the DEPENDS argument, but nothing I have tried works.

Here is a simplified version what I have:

function(run_my_special_rule target)

set (script_to_run ${CMAKE_SOURCE_DIR}/scripts/script.sh)

add_custom_command(
    TARGET ${target} PRE_BUILD
    COMMAND find ${CMAKE_CURRENT_SOURCE_DIR} -name "*.hpp" -exec ${script_to_run} {} +
    DEPENDS ${script_to_run}
)

endfunction()

Solution

  • You are mixing two different function signatures here. Check out the official documentation:

    1. https://cmake.org/cmake/help/latest/command/add_custom_command.html#generating-files
    2. https://cmake.org/cmake/help/latest/command/add_custom_command.html#build-events

    The former can have a DEPENDS statement while the later can have a TARGET statement. You can't mix both.

    In your case DEPENDS will just be ignored and the custom command will only be run when the original target is being built.

    You have to create an additional file to compare timestamps against. This minimal example should get you started:

    cmake_minimum_required(VERSION 3.20)
    project(custom_file_target VERSION 1.0.0)
    
    add_executable(main main.cpp) # main target
    
    add_custom_target(
        custom
        DEPENDS ${CMAKE_BINARY_DIR}/output.txt
    )
    
    add_custom_command(
        OUTPUT ${CMAKE_BINARY_DIR}/output.txt
        COMMAND echo your actual custom command
        COMMAND touch ${CMAKE_BINARY_DIR}/output.txt
        DEPENDS ${CMAKE_SOURCE_DIR}/dependency.txt
    )
    
    add_dependencies(main custom)
    

    As a side note: You have to make sure that your main target actually depends on the right files (i.e. also on the generated ones from your script - excluding output.txt).