I would like to invoke a C++ function from within a C file and I have read about the extern "C" construct and the wrapper API. However, I am unsure how to organize the various header files and how to link the object files.
Assume I have a C file MyProg.c and its corresponding header file MyProg.h.
Now, I created two files Wrapper.cpp and Wrapper.h that declare the function I wish to call from MyProg.c
// Wrapper.h
#include "Utility.h"
#ifdef __cplusplus
extern "C" {
#endif
void func_to_invoke();
#ifdef __cplusplus
}
#endif
Note that Wrapper.h includes a file that contains other utility C++ functions.
The question is how to compile and link the files. Should I do the following:
g++ -c Utility.cpp Utility.h
g++ -c Wrapper.cpp Wrapper.h Utility.h
gcc -c MyProg.c MyProg.h Wrapper.h
gcc MyProg.o Wrapper.o
EDIT:
I have tried the following and I still can't compile. I have pages and pages of errors related to the C++ libraries. Should I also declare all the functions in Utility.h within a __cplusplus macro?
g++ -c Utility.cpp
g++ -c Wrapper.cpp
gcc -c MyProg.c
g++ MyProg.o Wrapper.o Utility.
SOLUTION:
Utility.h must be removed from Wrapper.h and included in Wrapper.cpp
you should include Utility.o in the last line.
Do not include a .cpp file in your Wrapper header. That is entirely the wrong thing to do. Do not even include the Utility.h header. Just define your wrapper function. Then in Wrapper.cpp include the Utility.h header and define the wrapper function.
If your C++ code uses exceptions or runtime type information you will need to do the final link with g++. Your program will need the C++ support library.
I would write it like this:
Once you've compiled
Wrapper.cpp
into object code, it really doesn't matter whether its contents were previously written in C or C++, as long as you useextern "C"
to tell the compiler to skip name mangling forfunc_to_invoke
.If I remember well, both
gcc
andg++
can detect whether their input files contain C or C++ code and do the right thing, butgcc
will link against the C standard library andg++
against C++'s, so it's possible that you end up with some missing functionality.I think the best course of action would be to use
gcc
for anything that doesn't use any C++ feature, as it would be the case with C, andg++
for everything else.