CMake resolving tricky cyclical static link

CMake does not appear to have a way to programmatically specify linker options like

-Wl,start-group

to static link cyclically dependent targets with ld. Simply manually specifying this option is not desirable as not every linker uses this option. Sometimes the target LINK_INTERFACE_MULTIPLICITY can be set to a large enough number to fix such issues–but that doesn’t always work. CMake docs suggest the trickiest cyclical static link cases may require Object Libraries as discussed in the next section.

This 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 adds --start-group ld option automatically, but CMake didn’t seem to have such a facility.

Fix

We determined there was no benefit from having two library files for each language. 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.