Search code examples
cmakebuildcode-generationcmake-custom-command

CMake rebuilts custom target despite no sources having changed


I'm using a custom target in a CMake file of mine, which looks like this:

add_custom_target(generated_bar
    COMMAND ${CMAKE_COMMAND} -DOUT=bar -P generate-bar.cmake
    BYPRODUCTS bar
    COMMENT "Generating bar from foo"
    SOURCES foo)

This works fine for me, and bar gets generated. However, if I make generated_bar again - bar gets generated again, even though the source file foo has not changed.

Why is this happening?

Note: This question is related.


Solution

  • A custom target is always considered to be out of date, so its command always runs. However, that does not extend to its dependencies:

    add_custom_command(
      OUTPUT bar
      COMMAND ${CMAKE_COMMAND} -DOUT=bar -P generate-bar.cmake
      DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/generate-bar.cmake" foo
      COMMENT "Generating bar from foo"
    )
    
    add_custom_target(
      generate_bar
      DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/bar"
    )
    

    You should think of a custom target as like a .PHONY rule in Make... it's there to help you sequence things or to provide special utilities as build rules (that are not "built" as part of ALL)