Search code examples
c++static-linkingdynamic-linking

How to use shared libraries in a static library without forcing end-users to link against these?


Let's say I'm working on a static library foo.a, which makes use of a function in bar.so.

How do I build this library in such a way that anyone who uses foo.a in their project doesn't have to explicitly link against bar.so?


Solution

  • What you can do in libfoo.a is make a call to dlopen to dynamically link libbar.so. Then, use dlsym to locate the function you want to use.

    typedef void (*BarFunctionType) (const char *);
    FunctionType barFunction;
    
    void initialize_foo_lib () {
        void *h = dlopen("libbar.so", RTLD_LAZY);
        BarFunctionType barFunction = (BarFunctionType) dlsym(h, "barFunction");
        // Note scary looking cast to get your function pointer.
        //... rest of code can call barFunction now
    }
    

    libbar.so should be a C library, or the function should be extern "C" if a C++ library, for you to find the function name properly. Otherwise you will need to mangle the name to find the function with dlsym. You can use objdump -T on the library to check if the names in the library are mangled.

    Realize there is still a dependency on libbar.so, but it is baked into your static library. So the user of libfoo.a does not have to add -lbar to the link line when they link in -lfoo.