Linking with dynamic library with dependencies

It looks like you are most of the way there already. Well done with your investigation. Let’s see if I can help clear up the ‘why’ behind it.

Here’s what the linker is doing. When you link your executable (‘main’ above) it has some symbols (functions and other things) that are unresolved. It will look down the list of libraries that follow, trying to resolve unresolved symbols. Along the way, it finds that some of the symbols are provided by libB.so, so it notes that they are now resolved by this library.

However, it also discovers that some of those symbols use other symbols that are not yet resolved in your executable, so it now needs to resolve those as well. Without linking against libA.so, your application would be incomplete. Once it links against libA.so, all symbols are resolved and linking is complete.

As you saw, the use of -unresolved-symbols-in-shared-libs, doesn’t fix the problem. It just defers it so that those symbols are resolved at run time. That’s what -rpath is for: to specify the libraries to be searched at run time. If those symbols can’t be resolved then, your app will fail to start.

It’s not an easy thing to figure out library dependencies because a symbol could be provided by more than one library and be satisfied by linking against any one of them.

There is another description of this process here: Why does the order in which libraries are linked sometimes cause errors in GCC?

Leave a Comment