Search code examples
gcclinkershared-librariesstatic-librariesstatic-linking

How do I statically link zstd library to my dynamic library?


I am trying to statically link zstd library(I have libzstd.a or libzstd.so) to my shared library libtest.so. The idea is that when deploying libtest.so in our application, we don't have to depend on libzstd.a or libzstd.so any more, so we have to statically link the zstd library.

I tried these:

cc  -fPIC -Wl,-soname=libtest.so -static-libgcc  -shared -o libtest.so myobjects.o -ldl -lc -L/path/to/libzstd -l:libzstd.a
cc  -fPIC -Wl,-soname=libtest.so -static-libgcc  -shared -o libtest.so myobjects.o -ldl -lc -Wl,-Bstatic -L/path/to/libzstd -l:libzstd.a
cc  -fPIC -Wl,-soname=libtest.so -static-libgcc  -shared -o libtest.so myobjects.o -ldl -lc /path/to/libzstd/libzstd.a

But they're all giving me this error:

/bin/ld: /path/to/libzstd/libzstd.a(zstd_common.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; 
recompile with -fPIC
/path/to/libzstd/libzstd.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
make: *** [libtest.so] Error 1

What are the problem here? Thank you!


Solution

  • All object files that are linked into a shared library must be compiled as Position Independent Code (compiler option -fPIC).

    The linker error:

    /bin/ld: /path/to/libzstd/libzstd.a(zstd_common.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; 
    recompile with -fPIC
    

    is telling you that the linkage of the shared library libtest.so needs the object file zstd_common.o from the archive libzstd.a, but that object file was not compiled with -fPIC.

    So you must rebuild libzstd.a from source, this time compiling the object files that it contains with -fPIC.