So lately, I have been trying to better understand how the symbol resolution with shared libraries works. I have created 2 shared objects (libfoo and libbar) and 1 executable (test). Consider following set of programs:
foo.c
#include <stdio.h>
void foo()
{
puts(__func__);
}
bar.c
#include <stdio.h>
extern void foo(void);
void bar()
{
puts(__func__);
foo();
}
test.c
#include <stdio.h>
extern void foo(void);
extern void bar(void);
int main()
{
puts(__func__);
foo();
bar();
return 0;
}
libbar depends on libfoo, and test depends on both libfoo and libbar:
gcc -c -Wall -fPIC foo.c bar.c
gcc -shared -o libfoo.so foo.o
gcc -shared -o libbar.so bar.o -L. -lfoo
Now while building test, I deliberately don't provide the direct dependency on libfoo:
cheshar@editsb:~/2-test $ gcc -o test test.o -L. -lbar -Wl,-rpath-link=.
/usr/bin/ld: test.o: undefined reference to symbol 'foo'
./libfoo.so: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
cheshar@editsb:~/2-test $ ldd libbar.so
linux-vdso.so.1 => (0x00007ffe27bf7000)
libfoo.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f7d203e0000)
/lib64/ld-linux-x86-64.so.2 (0x00007f7d209ac000)
As we can see that test needs symbol foo and depends on libbar which in turn depends on libfoo and has the required symbol. So my question is why can't the linker resolve the symbol? Shouldn't it be able to scan all the dependencies and link to make the executable?