I've found something interesting during my C/C++ development under Linux. For instance, there are 2 shared libraries:
libfoo.so, which contains 1 function:
//------------libfoo.h-----------------
void func_foo();
//------------libfoo.c-----------------
void func_foo() { return; }
libbar.so, which contains 2 functions. And one of them is dependent of libfoo.so:
//-------------libbar.h---------------
void func_bar1();
void func_bar2();
//-------------libbar.c---------------
#include "libfoo.h"
void func_bar1() { return; }
void func_bar2() { return func_foo(); }
But if a program only calls func_bar1(), which is independent of libfoo, the gcc/ld still tries to search the symbol of func_bar2(), although the program doesn't need it at all. For instance:
//--------------------main.c------------
#include "libbar.h"
int main(int argc, char** argv)
{
func_bar1();
return 0;
}
Then I've got the following error by linking:
gcc main.c -L . -lbar
./libbar.so: undefined reference to `func_foo'
So I have to do so to make it work:
gcc main.c -L . -lbar -lfoo
It seems like that the linker can't resolve the symbol func_bar1() in main.o, so it has to look for it in the following library list: libbar.so. And all the symbols in libbar.so should also be checked, no matter if the main program needs them or not.. But I'm not sure of my understanding.
Could anyone please tell me, how the link really works in this case. And is it possible to avoid to link to the 'unnecessary' libfoo ?
Thanks in advance!
When a .so file is mentioned in a ld command, it will be treated as an usual .o file. As we know, all symbols in a .o file (in this case it turns out the libfoo.so) must be resolved. That's why even in the main program you don't call func_foo(), that function is still needed to be resolved.