Question

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++?

Was it helpful?

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

OTHER TIPS

Write your own C++ wrapper over those functions and declare your wrapper functions with extern "C".

I'm not aware of any other way.

The mangled name from the .lib file can be called from within your c program. If the .lib that you link to is stable, and not continually recompiled/updated, this solution might work for you.

I am not so familiar with windows, but How to See the Contents of Windows library (*.lib) or other searches should show how this information can be obtained from a .lib

Search for the name of the function in the output, most mangling will leave the name intact and just decorate it with all sorts of other information.

Place that name in your C code with an explanatory comment ...

Let us assume that you have a .c file (FileC.c) and you wish to call a function defined in .cpp (FileC++.cpp). Let us define the function in C++ file as:

void func_in_cpp(void) 
{ 
  // whatever you wanna do here doesn't matter what I am gonna say!
}

Do the following steps now (to be able to call the above function from a .c file):

1) With you regular C++ compiler (or www.cpp.sh), write a very simple program that includes your function name (func_in_cpp). Compile your program. E.g.

$ g++ FileC++.cpp -o test.o

2) Find the mangled name of your function.

$ nm test.out | grep -i func_in_cpp
[ The result should be "_Z11func_in_cppv" ]

3) Go to your C program and do two things:

void _Z11func_in_cppv(void);  // provide the external function definition at the top in your program. Function is extern by default in C.

int main(void) 
{
    _Z11func_in_cppv();   // call your function to access the function defined in .cpp file
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top