Linux calls different dynamic libraries and imports symbol conflicts

1 Problem description

Suppose there are two libraries libA.so, libB.so, which have the same function name TestFunc inside, but their implementations are different.

Example: In libA.so, function TestFunc prints "This is libA.so TestFunc "
           In libB.so, function TestFunc prints "This is libB.so TestFunc" 

Among them, the function TestFunc is used in the executable program program and connected through the dlopen() function.


Then found during the actual running of the program:

(1) Call dlopen() to obtain the symbols of the function TestFunc in libA.so and libB.so by exporting symbols in sequence.

(2) Call A->TestFunc in the program main program, and print "This is libA.so TestFunc".

(3) Call B->TestFunc in the program main program without any printing.


That is to say, according to the order of loading dynamic libraries, for the same function symbols in different function libraries, the address of the symbol loaded first is available, and the address of the symbol loaded later is wrong and cannot be located.

2 solutions

When creating a dynamic link library, add compilation options to gcc/g++ options

-Wl,-Bsymbolic.

Among them, Wl indicates that the parameters immediately following will be passed to the connector ld. Bsymbolic means that the local global variable definition is forced to be used, so that the global variable definition of the dynamic link library will not be overwritten by the definition of the same name in the application/dynamic link library

Guess you like

Origin blog.csdn.net/weixin_42121713/article/details/114320914