CMake's add_custom_command doesnt trigger rebuild of library

Hello,

Iam using CMake together with ninja to build a library. The library is depending on some code which may be generated before-hand by a custom command. The source for this code is within the source-tree and it must stay there, I have no freedom here.

Here’s my CMake code:

add_library(some_lib some_source.c)

#some_source.c may be modified by the following custom command
add_custom_command(
    COMMAND codegen.exe -i some_input.xml
    COMMAND ${CMAKE_COMMAND} -E touch "${CMAKE_BINARY_DIR}/generated"
    OUTPUT  ${CMAKE_BINARY_DIR}/generated
    DEPENDS some_input.xml
    COMMENT "Generating code ..."
)
add_custom_target(generate_something DEPENDS ${CMAKE_BINARY_DIR}/generated)
add_dependencies(some_lib generate_something)

Now if some_input.xml is changed I want to also rebuild some_lib. However in practice this code doesnt seem to work, the command is executed but after it is executed some_lib is not beeing rebuild, though the timestamps of the output files (some_source.c) of the custom command are newer than the library.

Can someone give me a hint on what am I doing wrong or how I can achieve this? Or is there a problem with CMake and ninja?

Thanks in advance, if you need more information please let me know.

Steve

If the custom command has some_source.c as output, specify it in OUTPUT argument so CMake can manage the dependencies:

add_custom_command(
    COMMAND codegen.exe -i some_input.xml
    COMMAND ${CMAKE_COMMAND} -E touch "${CMAKE_BINARY_DIR}/generated"
    OUTPUT  ${CMAKE_BINARY_DIR}/generated some_source.c
    DEPENDS some_input.xml
    COMMENT "Generating code ..."
)
add_custom_target(generate_something DEPENDS ${CMAKE_BINARY_DIR}/generated)

add_library(some_lib some_source.c)

Hi Marc,

thanks für your answer. I didnt want the file some_source.c to be deleted if a “cmake --build clean” is issued, thats why the OUTPUT option was no option for me. But I found the custom command option BYPRODUCTS. After specifying the sources which are modified by the generator tool to this option everything worked as expected.

Thanks very much for your help.

Kind Regards, Steve