There are two object files. They contain the definition (body) of a function. This object file was compiled using the C ++ compiler, so the function name is garbled. The second object file refers to (calls) the function from the first object file. However, the second object file was compiled using the C compiler, so the function name is not distorted. When linking these two object files, there is an error for the undefined character. It is not possible to modify the source files so that the C ++ object file uses extern "C" definitions and does not distort the function name. Nevertheless, you can write some kind of glue code (wrapper), compile it with the C ++ compiler and link it with these object files. Here is a simple example:
$ cat file1.cpp
int fun(int in1, int in2) { return in1+in2; }
$ cat file2.c
#include <stdio.h> int fun(int, int); int main() { printf("%d\n",fun(3, 4)); return 0; }
These two files are compiled into objects without any possibility of changing them:
g++ -c file1.cpp -o file1.o gcc -c file2.c -o file2.o
Writing glue code seems like a simple task, but the problem is that we have to export the function name in C and at the same time import it from C ++. The only solution I could come up with was to write two wrappers. One of them basically renames the C ++ function, and the other provides the renamed C function:
$ cat glue.cpp
int cppfun(int, int); #ifdef __cplusplus extern "C" { #endif int fun(int in1, int in2) { return cppfun(in1, in2); } #ifdef __cplusplus } #endif
$ cat gluecpp.cpp
int fun(int, int); int cppfun(int in1, int in2) { return fun(in1, in2); }
Compile and combine these wrappers with the original objects:
g++ -c glue.cpp -o glue.o g++ -c gluecpp.cpp -o gluecpp.o g++ file1.o file2.o glue.o gluecpp.o -o exe.out
Do you guys think there is another way? It became for me just an academic interest :)