Georg Schölly
Georg Schölly

Reputation: 126165

Is it possible to link to a shared library without access to the library itself?

I have the header files of a shared library but not the shared library nor its source code.

Can I still compile some code against this library?

If not, what information does the shared library contain which is not in the headers?

Upvotes: 6

Views: 3922

Answers (3)

Huazuo Gao
Huazuo Gao

Reputation: 1733

For those who just want it done, aside from using a dummy lib, there is another (probably even less robust) option: patchelf

Execute the following command after linking complete

patchelf --add-needed missinglib.so mylib.so

For CMake users, this can be done automatically by adding

add_custom_command(
    TARGET mylib POST_BUILD
    COMMAND patchelf --add-needed missinglib.so "$<TARGET_FILE:mylib>")

Upvotes: 2

bmargulies
bmargulies

Reputation: 100151

Yes. You can declare pointers-to-functions for them, and then call dlopen and dlsym, and off you go. However, trying to concoct somehow an executable or shared library which acts as if you've linked to the library is risky; see Employed Russian's answer for details.

You will need this libraries themselves to run the code, of course.

However, note that not all 'shared libs' are just shared libs. In some cases, there is a .a file that is used at link time to supply some statically linked code in addition to the .so at runtime. This is not common.

Upvotes: 3

Employed Russian
Employed Russian

Reputation: 213897

Can I still compile some code against this library?

Compile: yes. Link: maybe.

You can create a dummy library to link against. E.g. if the header contains:

int library_func(void*);

then:

// dummy_lib.c
int library_func(void *p) { return 0; }

gcc -fPIC -shared -o libfoo.so dummy_lib.c

# Now you can use libfoo.so to link your program.

There are some gotcha's:

  1. The real library may have SONAME of something other than libfoo.so (e.g. libfoo.so.2). There is no way for you to know without access to the real libfoo.
  2. The real library could use versioned symbols. If you link your program against the dummy library, it will use default version of all referenced symbols, which is likely to be correct now, but is likely to break in the future (if/when the real library is updated with a new and incompatible implementation of any symbols you call).

Upvotes: 6

Related Questions