The problem of link order when dynamic link libraries depend on each other

Viewed 66

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

1 Answers

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.

Related