-1

I have a C++ code that links two shared libraries (let's say, foo1.so and foo2.so). In both libraries I have a class called "Mesh", and the compiler cannot know which one I am trying to use when I try to instantiate the class Mesh (obviously I know which one I want to instantiate). I get the "error: reference to ‘Mesh’ is ambiguous"

Of course I could alter the source code of one of the libraries, wrapping the Mesh class around a namespace and that would solve the problem. I would like to avoid changing the library's code, though. Is there a way to remove this ambiguity in the source file which uses the libraries?

Thank you, Rafael.

  • 1
    Sorry, but the answer is no. You can not differentiate other than by using namespace. This is why per-library namespace is considered a good thing. – SergeyA Mar 01 '21 at 16:59
  • Are these dynamic or static libs? [This answer](https://stackoverflow.com/a/9183400/669576) mentions creating 2 dynamically linked libs - each one statically links to one of the conflicting libs. – 001 Mar 01 '21 at 17:00
  • If you are using dynamic libraries, you can load each dynamicaly (see [dl](https://tldp.org/HOWTO/Program-Library-HOWTO/dl-libraries.html) ) and then use the handle to differentiate the calls. – frachop Mar 01 '21 at 22:12

1 Answers1

0

By using dynamic libs (.so in linux), you can load each one and use each handle to differentiate call. See Dynamically Loaded (DL) Libraries

For example :

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>

class Meshib
{
    void * _handle;
    double (*_cosine)(double);

public:
    Meshib( const char * libraryPath)
    {
        char *error;

        _handle = dlopen (libraryPath, RTLD_LAZY);
        if (!_handle) {
            fputs (dlerror(), stderr);
            exit(1);
        }
        
        _cosine = reinterpret_cast<decltype(_cosine)>( dlsym(_handle, "cosine") );
        if ((error = dlerror()) != NULL)  {
            fputs(error, stderr);
            exit(1);
        }
    }

    ~Meshib() {
        dlclose(_handle);
    }

    double cosine(double v) { return (*_cosine)(v); }
};



int main(int argc, char **argv)
{
    Meshib meshLib1( "foo1.so" );
    Meshib meshLib2( "foo2.so" );

    printf("%f\n", meshLib1.cosine(2.0));
    printf("%f\n", meshLib2.cosine(2.0));
}

See this article for C++ class dynamic load.

frachop
  • 191
  • 1
  • 7