clinuxgcc

Possible to build a shared library with static link used library?


I can build a executable with gcc with static link:

gcc -static xxx.c -o xxx

So I can run xxx without any external dependent library.

But what if I want to build shared library without externel dependent library? which I mean I want the shared library statically linked its externel reference in.


Solution

  • This will work:

    # Generate position independent code (PIC)
    gcc -fPIC -c -o xxx.o xxx.c
    
    # Build a shared object and link with static libraries
    ld -shared -static -o xxx.so xxx.o
    
    # Same thing but with static libc
    ld -shared -static -o xxx.so xxx.o -lc
    

    A clarification: the -static flag, if given to gcc, is passed on to the linker (ld) and tells it to work with the static version (.a) of a library (specified with the -l flag), rather than the dynamic version (.so).

    Another thing: On my system (Debian) the last example gives a libc.a ... recompile with -fPIC error. Pretty sure that means that the libc.a I have on my system wasn't compiled with -fPIC. An apt-cache search libc pic did give some results however.

    See also: Program Library HOWTO, SO: combining .so libs, ld(1), gcc(1)