CMake resolve cyclical static link

CMake can automatically determine linker grouping via LINK_GROUP that adds linker flags like GCC:

-Wl,start-group

to static link cyclically dependent targets .

Alternatives

Target LINK_INTERFACE_MULTIPLICITY doesn’t always work. CMake docs suggest the trickiest cyclical static link cases may require Object Libraries as discussed in the next section.

A project had three targets (static libraries) that were always used like:

libfoo.a libfooC.a

or

libfoo.a libfooFortran.a

and the target code reference each other extensively, such that the linker gives up when ld –start-group isn’t used. Meson build system also adds --start-group ld option automatically.

To keep the targets with distinct compile definitions (including for “foo_src”), we used CMake Object Libraries:

add_library(tmp OBJECT ${foo_src})

add_library(fooC ${c_src} $<TARGET_OBJECTS:tmp>)
add_library(fooFortran ${fortran_src} $<TARGET_OBJECTS:tmp>)

Note, there is no “libtmp” created–only the object files from the “foo_src” will be created.