4

Is it possible to use CMake to enclose a target's libraries in --start-group/--end-group without manually writing the argument string into target_link_options?

Background: I'm having library ordering issues when linking a C++ executable to a list of libraries (using g++ 7.5.0). I recently learned about the --start-group and --end-group options in gcc/g++ that allow for repeated searching of archives. I would like to enable these options when using CMake to generate my build files.

Given a list of target library names (e.g. target_link_libraries(myTarget mylibrary1 mylibrary2 ${MY_VARIABLE_LIST_OF_LIBRARIES} ...)), is it possible to enclose all those libraries within --start-group/--end-group without having to manually type out the arguments as in target_link_options(myTarget PUBLIC "--start-group -lmylibrary1 -lmylibrary2 ... --end-group")? (I'd especially like to avoid having to track down the contents of ${MY_VARIABLE_LIST_OF_LIBRARIES}" to manually add -l to all libraries included in that variable.)

1 Answers1

5

CMake 3.24 introduces LINK_GROUP generator expression, which allows to group libraries in target_link_libraries command for adding some feature on that group. One of the group features is RESCAN, which effectively adds --start-group/--end-group for a GNU compiler:

target_link_libraries(myTarget
  PRIVATE # or any other keyword
  mylibrary1 mylibrary2 # These libraries will be linked normally
  "$<LINK_GROUP:RESCAN,${MY_VARIABLE_LIST_OF_LIBRARIES}>" # These libraries will be grouped
)
Tsyvarev
  • 60,011
  • 17
  • 110
  • 153