Search code examples
c++static-librariesstatic-linking

Suggestions for static library to avoid name collision


We have two libraries - lib1 and lib2. Both the libs use a third lib say lib3. If our customer uses lib1 and lib2 in the same application using static linking, the customer faces linking issues due to symbol collision as functions from lib3 are common in lib1 and lib2.

We have access to lib1, lib2, lib3 source codes. What changes should we do to avoid naming collisions?

After reading some posts, namespacing in C++ seems to solve the problem? But will it work in our case as lib3 will still be loaded twice?


Solution

  • We finally fixed our problem using dynamic namespacing

    First, define a macro for the namespace

    #ifndef LIB_NAMESPACE
    #define LIB_NAMESPACE SomeNameSpace
    #endif
    

    then add namespace around every class.

    On compilation override the macro from the compiler command line e.g.

    g++ -DMY_LIB_NAMESPACE=Lib1Namespace ...
    g++ -DMY_LIB_NAMESPACE=Lib2Namespace ...
    

    The only disadvantage is the size of the final executable will be slightly larger due to duplicate code.