How do you call a function with the same symbol in 2 different shared libraries?
-
25-07-2021 - |
質問
I have several versions of the same library written in C++. I need to compare them side-by-side. These libraries use the same namespace, function names and take the same parameters.
Are there any methods to control which version of the library I use when I link two or more of them at the same time?
解決
You cannot link two libraries with identical symbols and get access to both. However, you can build your own thin wrapper libraries to disambiguate the two versioned libraries:
- Define an abstract class
Wrapper
that exercises the functions of the target library using abstract virtual functions - Define an implementation of
Wrapper
in a class calledWrapperImpl
that calls through to the target library from the virtual methods - Define a free-standing method
Wrapper *MakeImpl
returningnew WrapperImpl()
- Compile
WrapperImpl
into static libraries several times, linking with different versions of the target library each time. Critical: pass-DWrapperImpl=WrapperImplV1 -DMakeImpl=MakeImplV1
to the compiler, withV1
,V2
,V3
, and so on, for different versions. You should end up with multiple libraries. - Link your main tester with these multiple libraries
At this point, your main tester has access to free-standing functions MakeImplV1
, MakeImplV2
, MakeImplV3
and so on created through renaming MakeImpl
through the preprocessor. Use these functions to obtain instances of Wrapper
that call through to different versions of the target library.