How to use `--start-group` and `--end-group` in CMake
Asked Answered
F

2

8

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.)

Fairlead answered 7/9, 2022 at 17:50 Comment(0)
G
10

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
)
Graniah answered 7/9, 2022 at 21:5 Comment(0)
E
1

Use CMAKE_<LANG>_LINK_GROUP_USING_<FEATURE>:

set(CMAKE_CXX_LINK_GROUP_USING_cross_refs_SUPPORTED TRUE)
set(CMAKE_CXX_LINK_GROUP_USING_cross_refs
  "LINKER:--start-group"
  "LINKER:--end-group"
)
target_link_libraries(
  myTarget
  "$<LINK_GROUP:cross_refs,your_lib1, external_lib>"
)
Electro answered 9/3, 2024 at 2:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.