Triang3l
Triang3l

Reputation: 1238

Creating shared library that depends on another shared library using ld

I want to create a shared library libdependent that uses certain exported functions from libparent using header files.

The path of libparent is not known on the build stage, so I can't use rpath, and I call dlopen("path/libparent.so", RLTD_NOW | RTLD_GLOBAL) and dlopen("path/libdependent.so", RLTD_NOW | RTLD_GLOBAL) on run time instead.

But there are no references to libparent in libdependent file at all if I put libparent.so into a library search path during linking and use -lparent.

When I try to dlopen libdependent, I get "cannot locate symbol" error, even though RTLD_GLOBAL is set.

What should I do to use exports from libparent without calling dlsym?

Upvotes: 2

Views: 2053

Answers (2)

Triang3l
Triang3l

Reputation: 1238

Solved by adding -shared to the linker options and specifying the library in -l. -( can also be useful.

Upvotes: 0

Oleg Olivson
Oleg Olivson

Reputation: 499

First of all, when you want to create a library, you don't have to import it, so

dlopen("path/libdependent.so", RLTD_NOW | RTLD_GLOBAL)

is not needed.

Second, if you don't know exactly the name of library (libparent) you will use, you have to use dynamic linking and dlopen. In dynamic linking you don't have to inform linker about your libparent library, but you have to use dynamic linker library, so linker command will be like this:

g++ -o output -dl input.cpp

dl says that you will use dlopen.

Whe using program, be sure that your libparent.so is visible from running directory (or use absolute path). Also check return value of dlopen to know about success of library opening.

    void *handle = NULL;
    handle = dlopen("libparent.so", RTLD_LAZY);
    if(!handle){
        printf("Error!\r\n");
    }

Hope it helps.

Upvotes: 1

Related Questions