Search code examples
c++cname-mangling

Using C++ mangled functions from C


I have a .lib file, source code of which I don't have.

I need an exported function from it, but I'm writing in C, and the function is C++ name-mangled. I can't write extern "C", because I don't have the source code.

How do I link mangled function without source code and switching to C++?


Solution

  • Make C++ wrapper:

    wrapper.cpp:

    #include "3rdparty.hpp"
    
    extern "C" int foo(int a, int b)
    {
        return third_party::secret_function(a, b);
    }
    

    consumer.c:

    extern int foo(int, int);
    
    // ...
    

    Build: (e.g. with GCC)

    g++ -o wrapper.o wrapper.cpp
    gcc -o consumer.o consumer.c
    g++ -o program consumer.o wrapper.o -l3rdparty