Search code examples
c++cmakefilelinkerlegacy

Calling a C++ Function from C Program


I am working on adding a function written in C++ to a large program written in C.

I have tried to surround all of the codes included in the C program in extern "C" blocks, but when I compile with g++, I still get the errors coming from compiler trying to compile C as C++. I have added the extern "C" blocks to all the headers and .c files as follows:

#ifdef __cplusplus
extern "C"
{
#endif

//C code here

#ifdef __cplusplus
}
#endif

The errors look like this:

./sortcodes/oci.c: In function ‘int GetSpecList(ClientData, Tcl_Interp*, int, Tcl_Obj* const*)’: ./sortcodes/oci.c:188:25: error: ‘init’ does not name a type static init=TRUE;

These errors do not occur if I remove my C++ function call and just compile the C program with gcc.

If I remove the extern "C" blocks and compile using options

gcc -std=c++0x -lstdc++ -std=c++11

I get errors like the one below, where C++ flags were obviously ignored

./Event_Reader.cpp:9:20: fatal error: iostream: No such file or directory #include

Are there any options that I am missing or misinterpreting? Any advice would be appreciated.


Solution

  • First, to compile the c++ code you have to use a c++ compiler like g++ or clang++. Then, you need to declare the desidered c++ function with extern "C" linkage. At this point you can call the function from the C code. Refer to How do I call a C++ function from C for a concrete example.