How to create file-dependency for all sources of target?

I have different use-cases where I would like to declare a file-dependency at target-level, be it generated or in the sources, which influences the compile-process for all sources of this target.

Imagine a configuration-file for the compiler (added with target_compile_options()), or generated meta-information used for optimisations.

I’m now using set_source_files_properties(.. PROPERTIES OBJECT_DEPENDS ...) but this applies it globally to the source-file and thus is used in other target (where the same source file is compiled) and the dependency does not yet exist (and cannot, it is created in a later stage).

Is there something like set_target_properties(.. ALL_SOURCES_DEPENDS ..)?

You should probably do this in two stages. Something like:

    OUTPUT "MyProj.conf"
    COMMAND generate_conf # first arg is a target or an executable in the PATH
    DEPENDS generate_conf # ... other targets, files

add_custom_target(GenerateMyProjConf DEPENDS "MyProj.conf")

add_executable(MyProjExe Src1.cpp)
target_compile_options(MyProjExe PRIVATE -some_flag "${CMAKE_CURRENT_BINARY_DIR}/MyProj.conf")
add_dependencies(MyProjExe GenerateMyProjConf)

Keep in mind the limitations of add_dependencies:

Makes a top-level depend on other top-level targets to ensure that they build beforedoes.

See the DEPENDS option of add_custom_target() and add_custom_command() commands for adding file-level dependencies in custom rules. See the OBJECT_DEPENDS source file property to add file-level dependencies to object files.

This means, MyProjExe is NOT rebuilt when MyProj.conf changed!
Therfore you should probably use a combination of both your (Alex and Patrick) suggestions.

If the a dependency to MyProj.conf is changed, MyProj.conf is regenerated, but Src1.cpp is not recompiled. Unfortunately this is not the solution.

OBJECT_DEPENDS does sound like the right thing, but as you noticed, source file properties apply to all usages of the file. I suggest somehow giving the file another name so that CMake doesn’t see it as the same file (copy it during the build then compile that file per target, use a symlink, something even more creative perhaps). I’d also like to see source file/target combo properties, but I don’t know how to specify it. Maybe $<$<STREQUAL:$<TARGETI_NAME>,WithConf>:-flag ${CONF}> works?

Copying the file during build came to my mind as well.

And I think I know why there is no way to have this feature: How would you write this in a GNU Makefile?