C – Link order issues when dynamic link libraries depend on each other

Link order issues when dynamic link libraries depend on each other… here is a solution to the problem.

Link order issues when dynamic link libraries depend on each other

Sorry my English is not good.

When GCC compiles, if main.o depends on liba.so, liba.so depends on libb.so

Then you should link liba.so first and then link libb.so. The opposite will be wrong

The reason I learned is that:

The compiler will iterate through all the .o, .so modules in turn, and put undefined symbols in list U

In the process of going through all the .o,.so modules in turn, the symbols in .

o,.so are used to interpret the symbol in the list >U

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

So if liba.so and libb.so depend on each other, I theoretically need to link them like this:

-la -lb -la

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

Why?

Did I learn the linking principle wrong, or did the compiler optimize

Solution

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 are doing it the other way around: 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 affects only the archive library.

Unlike archive libraries, when you link a shared library, you get the entire library, so if it appears once in the link row, you don’t need to repeat it again.

To understand why you might need to archive a library repeatedly on a linked line, read this

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

The “principle” you said is wrong (inverted), the compiler is not involved in the linking phase at all.

Related Problems and Solutions