1

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • You probably expect options `BYPRODUCTS` and `SOURCES` are for specifying *dependencies*, but they are not. According to the [documentation](https://cmake.org/cmake/help/latest/command/add_custom_target.html), `SOURCES` specifies files for IDE only, and `BYPRODUCTS` is used only by Ninja generator. – Tsyvarev Oct 26 '21 at 20:09

1 Answers1

1

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)

Alex Reinking
  • 16,724
  • 5
  • 52
  • 86
  • 1
    Wow, the amount of code I'm going to have to write just to get a file to be compiled in two languages is staggering: A generator generation command, A generator invocation in the custom cuoomand, and a custom target to block the auto-rebuild... – einpoklum Oct 26 '21 at 19:45
  • https://gitlab.kitware.com/cmake/cmake/-/issues ;) – Alex Reinking Oct 26 '21 at 19:52
  • https://gitlab.kitware.com/cmake/cmake/-/issues/22779 :-( – einpoklum Oct 26 '21 at 19:57