1

My program can make use of a certain library (let’s call it foo), and this library is non-free. So I don’t want to make it a dependency neither at compile time nor at run time. The library only provides nice-to-have extra features, so the program can do without foo. So I’m planning to do this:

  • Let configure look for foo at compile time, and if not present, build the program without the extra features. This part is easy enough.
  • If foo is present then #include foo.h, but don’t link to the shared library (because the program must be able to run without foo present), and instead use dlopen(foo.so) and dlsym().

So why do I want to include foo.h if I am going to use dynamic linking anyway? Well, because foo.h has all the definitions of the data types and enumerations I am going to need when using the functions in the library. There are a lot of these, and some of them are complex, so it seems like an easy way to get hold of them. And it seems to be working in my first tests.

However, I can’t find any examples of dlopen() usage where the library header is also being included, so I’m afraid I’m doing something completely stupid. I’ve never worked with dynamic linking before. So is this the proper way to do this?

2 Answers2

0

This will depend on the linker used. Most linkers today support so called "lazy" linking of libraries where the linker will create glue code that will only attempt to load the library on first use. This does not work with any library, but for most shared libraries this is fine. You can then use dlsym/RTLD_GLOBAL to test wether the library is available and if not just not call those functions.

Os X linker supports lazy linking with -lazy-l[lib]. For linux I believe it is -z lazy -l[lib], but I never tried that on Linux.

Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • I use lazy linking, and it works ok. The code in question is this: https://github.com/ejurgensen/forked-daapd/blob/spotify/src/spotify.c. I think there are two problems with it: 1) I'm include libspotify/api.h to get the data types, contrary to all examples I have seen, 2) Assigning the function pointers is an ugly three step process – user3333422 Mar 11 '14 at 09:04
0

Probly irrelevant by now but what you are looking for is an import library i.e. a stub library which would provide fake function symbols which, when called, would search and load library via dlopen and redirect to real implementation.

Example of how this could be achieved is given in this answer. You can also use Implib.so tool to automatically generate import library for a given shared library.

yugr
  • 19,769
  • 3
  • 51
  • 96