3

When compiling a program with static libraries, it was suggested to me from many sources (including SO community) to include the library twice.

As in:

gcc main.c -lslA -lslB -lslC -lslA -lslB -o final
  1. Does this result in a bigger executable (.i.e. is the linker smart enough to avoid double inclusion?).

  2. Is this (multiple inclusion) the proper solution or a workaround (.i.e. will there always exist a more proper, even if harder way to handle it)

4
  • 1
    No, it will not make the executable bigger. Commented Apr 11, 2013 at 10:53
  • @n.m. I did not expect that. Which brings me to the question: why doesn't the linker do that automatically .i.e. look for undefined references in the other linked libraries .i.e. why does ordering matter.
    – aiao
    Commented Apr 11, 2013 at 10:57
  • 1
    If you need it multiple times on the linker line, then this sounds more like messed up dependencies
    – PlasmaHH
    Commented Apr 11, 2013 at 10:57
  • 1
    The linker looks for dependencies linearly. If you have -lA -lB, the linker goes like this: process A, forget it for good, process B. If B depends on A, and the relevant symbols were not already pulled, the link will fail. Including a library multiple times is a way to cope with circular dependencies. --start/end-group is another (GNU-specific) way. It's better to not have any in the first place though. Commented Apr 11, 2013 at 11:08

1 Answer 1

17

The only reason to include the library multiple times is, for example, if slA requires a symbol resolved by slB but slB requires a symbol required by slA. The linker does a single pass to resolve symbols, but repeating your library causes, in effect, a second pass on that library. It won't change the size of your output, but it's not necessary either:

Instead of presenting your libraries multiple times, you can tell the gcc linker to group certain libraries together -- letting it do what it needs to resolve the symbols within that group. For example:

gcc main.c -Wl,--start-group -lslA -lslB -lslC -Wl,--end-group -o final

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.