4

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?

7
  • I know this is possible, because SFML doesn't require me to link -lX11 or -lGL. Commented Jul 6, 2012 at 21:23
  • 2
    I'm pretty sure, that you can't do this, unless you get a static library of bar, for your example - bar.a (as I already said in your other question, I just can't give more information, as I'm not familiarized with SFML or XLib) Commented Jul 6, 2012 at 21:39
  • What is your goal? Do you just want to avoid the reference to bar.so at link-time because that is more convenient? Or do you want to be able to swap out bar.so with someother.so without re-linking? Commented Jul 6, 2012 at 22:02
  • No, I want people to not need to link against -lGL, -X11 and any other dynamic library I need to use. Commented Jul 6, 2012 at 23:04
  • In that case, the dlopen mentioned by user315052 is an overkill IMO. What you gain is hardly worth the extra coding effort and maintainability issues. Better stick with the extra linker options, there is no easy way to avoid them. Commented Jul 7, 2012 at 0:41

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Judging from the extensions, you are looking for a Unix way; to my knowledge, both g++ and clang++ can't do this.

Visual C++ can probably do it -- I've only used it for static libraries, not DLLs, but...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.