How to rerun cmake custom command, when one of its dependencies becomes "dirty"?

I have python script that is run through add_custom_command in my project, this script analyzes target sources and generate additional one for the target.

get_target_property(TARGET_SOURCES ${target} SOURCES)
     OUTPUT ${CMAKE_BINARY_DIR}/static_init/generated/${target}/static_init.cpp
target_sources( "${target}" PRIVATE "${CMAKE_BINARY_DIR}/static_init/generated/${target}/static_init.cpp" )

I need my script to rerun when one of sources becomes “dirty” (e.g. one of included headers is changed, probably this file is in another target and it is not guaranteed that another target will be rebuild on header change). As we use Ninja, IMPLICIT_DEPENDS isn’t available for us, so it looks DEPFILE property is the way to do it, but I cannot understand, how can I get one for all ${TARGET_SOURCES}?

It doesn’t seem to me that ninja will generate something like that automatically, I cannot write it by hands, as it will require to recursively analyze all includes during cmake run. Or maybe there is another way to solve this problem?

You’ll need your script to write out a Makefile-like snippet describing the files it read. Like gcc’s -M flags do. You can then use that file as a DEPFILE argument on the custom command.

You meen I need to resolve all included headers recursively for that?

Any that matter, yes. If your script just reads the contents and ignores #include directives, you can skip those.

And is there a way to pass those dependencies to be checked at compile time? It seems that DEPFILE is a way to do it, but I don’t understand, how it must look. I understood that I can easily get all headers as byproduct of my script, but only after first compilation.

If it’s OK to run the script after compilation of those sources, you can simply add their object files as dependencies: