Target dependant properties of a source file used by multiple targets

Consider a project that defines multiple object libraries from the same source file:

add_library (A OBJECT
  foo.cpp
  bar.cpp
)

add_library (B OBJECT
  foo.cpp
  bar.cpp
)

My goal is to set a preprocessor definition (say FOO) specifically for foo.cpp to a value dependent on the target that generates the corresponding object file. In particular, I want to avoid a target-wide visibility of the definition, e.g., by using target_compile_definitions.

Is there a way to limit the scope of set_source_files_properties to specific targets? I feel that a generator expression would be the appropriate tool here, something along the lines

set_source_files_properties (foo.cpp PROPERTIES COMPILE_DEFINITIONS
  $<$<TARGET_SOURCE:A>:FOO=A>
  $<$<TARGET_SOURCE:B>:FOO=B>
)

However, I’m not able to identify an existing (target-dependent) generator expression that is suitable for this purpose.

The proper way to do this is to define different targets for the different combinations of macro definitions and link against those different targets to pick up the different versions of the files.

Just because it is an object library doesn’t mean the file is recompiled for each target that links against the object library (that would, in fact, defeat the purpose of object libraries).

Are you suggesting the use of single source targets? While that certainly would work, the approach does not come as proper but rather as a workaround for a CMake-inherent limitation causing unnecessary boiler plate.

Unfortunately, I’m not following in reference to what is the second part of your answer since there’s no linking involved in the original question.

You want the same source file compiled in different ways, right?

How a source file is compiled is determined by the target that contains that source file.

Therefore, if you want source files built in different ways, the source file must be included in multiple targets, one for each way you want the source file built.

There are different ways to achieve this.

That’s exactly why I include the same source file in two different targets in my original example.

What I’m missing is a finer control over the properties of certain source files belonging to each of those targets. set_source_files_properties and set_property (SOURCE ...) are seemingly intended for that purpose. However, these commands do not differentiate between the targets a source is part of and instead apply the properties unconditionally. The latter is something I would like to avoid.