Search code examples
gcclinkage

GCC: Statically adding an external shared-object to the compilation


I have 2 C libraries:

  1. A dependency library, compiled as a shared-object
  2. My library - which I also want to compile as a shared-object

I want to compile my library into a shared object, but I do not want the dependency library to be loaded on runtime.

I.e. I want the dependency library to become a part of the shared-object I create from my library, so one won't have to add the dependency to LD_LIBRARY_PATH when using my library.

How can I do it with GCC?


Solution

  • This seems to be a XY problem: You want to add a SO statically to avoid using LD_LIBRARY_PATH. Allow me to address the latter and ignore the former. ;-)

    LD_LIBRARY_PATH is a means to temporarily overwrite the library search path. Note "overwrite": The paths given in LD_LIBRARY_PATH are searched first, and if a library is found in them, the standard search paths are not considered for that library. It "knocks out" other versions that might be installed in the standard paths. It's easy to see how this could have surprising and unwanted consequences. It is a debug feature, mostly, so you are right in not wanting to use it.

    There are three "correct" ways to address this:

    1) Install the dependency in one of the standard search paths (/usr/lib/* / /lib/*, check /etc/ld.so.conf for a list). This will require superuser priviledges.

    2) Add the path of the dependency to the standard search paths (in /etc/ld.so.conf). This will require superuser priviledges.

    3) Configure the path of the dependency into your library at compilation time (-Wl,-rpath=/path/to/lib/). This will add the given path to the paths searched by this library only. It does not require any special priviledges, and has none of the disadvantages that LD_LIBRARY_PATH has.

    As an aside, you can check where your binary does "find" its libraries via ldd <filename>.