Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 262
Sam Liao Avatar asked Aug 28 '09 03:08

Sam Liao


2 Answers

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)

like image 171
Inshallah Avatar answered Sep 18 '22 12:09

Inshallah


There's some neat hackery you can do with Rpath so that a ELF executable or .so will look for its dependent .so files first in the same directory as itself:

  • make a short script echo-rpath consisting of

    echo '-Wl,--rpath=$ORIGIN'

  • add that to your build command line as gcc -o file -lwhatever `echo-rpath ` objects

(The echo mechanism prevents Make or the shell from eating the $ sign and ensures it gets passed into ld.)

like image 41
pjc50 Avatar answered Sep 20 '22 12:09

pjc50