How can I avoid linking an unnecessary shared library?

I found something interesting while developing C / C ++ on Linux. For example, there are two 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 depends on 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 the program only calls func_bar1 (), which does not depend on libfoo, gcc / ld still tries to find the func_bar2 () symbol, even though the program doesn't need it at all. For example:

//--------------------main.c------------
#include "libbar.h"

int main(int argc, char** argv)
{
    func_bar1();

    return 0;
}

      

Then I have the following error, linking:

gcc main.c -L . -lbar
./libbar.so: undefined reference to `func_foo'

      

So I have to do this for it to work:

gcc main.c -L . -lbar -lfoo

      

It looks like the linker cannot resolve the func_bar1 () symbol in main.o, so it must look for it in the following library list: libbar.so. And all symbols in libbar.so must be checked as well, whether they need the main program or not. But I'm not sure about my understanding.

Can anyone please tell me how this link actually works in this case. And is it possible to avoid referencing the "unnecessary" libfoo?

Thanks in advance!

+3


source to share


1 answer


When a file .so

is mentioned in a command ld

, it will be treated like a regular .o

file. As you know, all characters in the file .o

(in this case it turns out libfoo.so

) must be resolved. So even in the program main

you don't call func_foo()

, this function is still needed to resolve.



0


source







All Articles