Search code examples
c++cword-wrapambiguity

How to use 2 C libs that export the same function names


Duplicate of the following question: C function conflict


Hi, in my current project I have to use some kind of interface lib. The function names are given by this interface, what this functions do is developers choice. As far as I can tell a project shall use this functions and when it comes to compiling you choose the lib and with it the functionality. What I try to do is to use an existing lib and my lib at the same time by wrapping the other and call it in mein functions:

otherlib:

int function1 (int a) {
// do something
}

mylib:

int function1 (int a) {
//my code here
    otherlib::function1(a);
}

Problem is I don't have access to the other lib and the other lib doesn't have any namespaces. I already tried

namespace old {
    #include "otherlib.h"
}

and then call the old function by old::function1 in my function. This works as long as it's only header file. The lib exports it's symbol back into global space. Also something like

namespace new {
    function1 (int a) {
        ::function1(a);
    }
}

didn't work. Last but not least I tried ifdefs and defines suggested here

but I wasn't successful.

Any ideas how to solve this? Thanks in advance.

EDIT: I neither have access to the old lib nor the project both libs shall be used in.

EDIT2: at least the old lib is a static one


Solution

  • Namespaces in C solved using library names prefixes like:

    libfoo --> foo_function1
    libbar --> bar_function1

    These prefixes are actual namespaces. so if you write libbar

    int bar_function1(int a) {
         function1(a);
    }
    

    This is the way to solve problems.

    C has namespaces --- they just called prefixes ;)

    Another option is to do various dirty tricks with dynamic loading of libraries like:

    h1=dlopen("libfoo.so")
    foo_function1=dlsym(h1,"function1")
    
    h2=dlopen("libbar.so")
    bar_function1=dlsym(h2,"function1")