3

Sorry for my bad english.

During GCC compilation, if main.o depends on liba.so, and liba.so depends on libb.so

Then you should link liba.so first and then libb.so. Conversely, an error will occur

The reasons I learned are:

The compiler will traverse all .o, .so modules in sequence, and put them into the list U if they encounter undefined symbols

In the process of sequentially traversing all .o, .so modules, the symbols in the .o, .so are used to interpret the symbols in list U

At the end of traversal, if there are still undefined symbols in U, an undefined symbol error is reported

So if liba.so and libb.so depend on each other, in theory i need to link them like this:

-la -lb -la

However, the actual operation shows that liba.so does not need to be linked twice

Why?

Is the link principle I learned wrong, or did the compiler optimize it

velscode
  • 75
  • 3
  • 1
    With static libraries, you might need to do what you hypothesize. With shared libraries, once one symbol is used, all the symbols are available, so the repeated libraries are unnecessary. There are options with modern linkers to automate the reprocessing of groups of static libraries. – Jonathan Leffler Aug 23 '21 at 02:30
  • There are options with modern linkers to automate the reprocessing of groups of static libraries. --> Does this mean I don't need to care about my static library link order? @JonathanLeffler – velscode Aug 23 '21 at 02:39

1 Answers1

3

if main.o depends on liba.so, and liba.so depends on libb.so
Then you should link liba.so first and then libb.so. Conversely, an error will occur

You got that backwards: if liba.so depends on libb.so, then the correct link order is -la -lb.

However, the actual operation shows that liba.so does not need to be linked twice

Why?

In general, for UNIX linkers, the order matters only for archive libraries.

Unlike with archive libraries, when linking shared libraries, you get the entire library, so if it appears on the link line once, there is never a need to repeat it again.

To understand why you might need to repeat an archive library on the link line, read this.

Is the link principle I learned wrong, or did the compiler optimize it

The "principle" you stated is wrong (backwards) and the compiler is not involved in the link stage at all.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362