0

I have a shared library A.so. There is a function foo() defined in it. This foo() function depends on a shared library libnl-1.so. The relationship is below:

A.so 
    {
      foo() => libnl-1
    } 

I have a program app. It calls two functions, foo() and bar(). bar() needs another version of libnl, libnl-3. The relationship is below:

app {
      foo()
      bar() => libnl-3
    }

I compiled app using cc -o app -lnl-3 -lA. But I found my app always crashes. It seems that foo() is calling into libnl-3 instead of libnl-1 (I have no idea how to verify this). Can anyone help me out? If I want to do this, what should I do? Change the linking order?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
HuangJie
  • 1,488
  • 1
  • 16
  • 33
  • You may use `$ LD_DEBUG=all ./app` to check from where the dynamic linker imports symbols to your program. – Sergio Feb 19 '17 at 17:28
  • Why do you think it is a good idea to link two versions of one library at the same time? You really need to rethink what you're doing so that you only use one version of the library, preferably the latest. – Jonathan Leffler Feb 19 '17 at 17:51
  • Why is the answer at http://stackoverflow.com/questions/228117/loading-multiple-shared-libraries-with-different-versions?rq=1 of no use for your case? (I just assume here that you cannot just C&P the two functions you need out of the libs because of them being closed source or whatever) – deamentiaemundi Feb 19 '17 at 18:21

1 Answers1

1

If I want to do this, what should I do?

On UNIX (unlike a windows DLL), a shared library is not a self-contained unit, and does not function in isolation. The design of UNIX shared libraries is to emulate archive libraries as much as possible. One of the consequences is that (by default) the first defined function "wins". In your case, libnl-3 and libnl-1 likely define the same functions, and you'll get the definition from whichever library is first (which will be wrong for one call, or the other).

Change the linking order?

That will change the first library, and will still be wrong.

So, what should you do?

The best option is not to link incompatible versions of the same library. Pick one of libnl-1 or libnl-3 and stick with it.

If you can't, you may be able to achieve desired result by linking A.so with -Bsymbolic, or by making bar use dlopen("libnl-3.so", RTLD_LOCAL|RTLD_LAZY) to lookup needed libnl-3 function instead of using it directly.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362