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.
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)
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With