Loading two different versions of the same shared library

你说的曾经没有我的故事 提交于 2020-05-16 01:12:53

问题


I'm in a situation that's quite similar to the following. There's libA.so that depending on some compile time flags exhibits slightly different behaviour (it's an external lib, and I can't modify the source). Then, I have libB.so that depends on libA.so (compiled with say -DVALUE=1), and in my executable I depend both on libB.so, as well as on libA.so, but compiled with -DVALUE=0. However, once I launch it, ld resolves all symbols with one of libA.so versions, so both my executable and libB.so are using the same functions.

Is there any way to specify that I want to load resolve undefined symbols of libB.so only using its dependencies? I've tried using -Wl,-Bgroup flag when building libB.so, but it didn't change anything. I know there's dlmopen that can load the library in a new namespace, but I'd like to have it loaded automatically at startup.

I'm attaching a set of files that reproduce the behaviour:

libA.so:

#include <stdio.h>

#define _STR(x) #x
#define STR(x) _STR(x)

#ifndef VALUE
#define VALUE default
#endif

void func2() {
    printf(STR(VALUE) "\n");
}

void func() {
    func2();
}

libB.so:

#include <stdio.h>

extern void func(void);

void b_func() {
    func();
}

executable:

#include <stdio.h>

extern void b_func(void);
extern void func(void);

int main() {
    func();    // should print "default"
    b_func();  // should print "other"
}

build commands:

gcc -fPIC -shared A.c -o libA.so
gcc -fPIC -shared -DVALUE=other A.c -o libA2.so
gcc -fPIC -shared B.c -L. -lA2 -o libB.so
gcc main.c -L. -lA -lB -o main

Curiously, it all works fine on OS X.

来源:https://stackoverflow.com/questions/40629041/loading-two-different-versions-of-the-same-shared-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!