Program use two conflicting shared libraries

2019-09-15 07:02发布

问题:

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?

回答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.