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

后端 未结 3 515
傲寒
傲寒 2020-12-29 10:33

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 lib

相关标签:
3条回答
  • 2020-12-29 10:59

    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)

    0 讨论(0)
  • 2020-12-29 11:09

    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.)

    0 讨论(0)
  • 2020-12-29 11:15

    If you have any plans on portability for your shared library, use libtool(1). It will handle most of the details of compiler flags for you and will make your life infinitely easier. If you don't use libtool, but later decide you want to port your program to OS X or Windows, you're going to end up reinventing it anyway.

    0 讨论(0)
提交回复
热议问题