How to run `add_custom_target` when source file changes

How do I ensure that when a source file changes, the custom target with command is re-run?

This is what I’m using

add_custom_target("gen_code"
    COMMAND run.py ${INPUT_FILE} -o ${OUTPUT_FILE}
    SOURCES ${INPUT_FILE}
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
    DEPENDS ${INPUT_FILE}
    BYPRODUCTS ${OUTPUT_FILE}
    # OUTPUT ${OUTPUT_FILE}
)

This does not re-run the command when the source file changes. Using the OUTPUT does not work either. What gives?

You should really use add_custom_command for commands with inputs and outputs. You can then have a nice gen_code custom target that depends on its outputs.

1 Like