|
||
Calling C++ from C |
||||
Occasionally you will find yourself in a position, particularly if you are porting older C code, where it would be convenient, if not necessary, to call a C++ routine from C code. A legal and portable way to do this is to define a C++ function with a C interface (note that this must be a global function, and not a member function). Such a function is defined in a .cpp file (C++ source) and declared using the extern "C" mechanism. This makes the function appear to be C-callable, but inside the function, you may make use of any C++ constructs that you wish. The function may only take C-style parameters (no classes, class pointers, references, etc.).
For example, suppose that you wish to call C++ function cpp_func from a .C file (C source). Then the technique is to define the function in a C++ file, but declare it in such a way that it has “C” interface. The following is an example:
|
||||
Header file |
The following code could be placed in an include file, or header file, to declare your C++ function with a "C" interface. Note how the extern "C" mechanism is wrapped by ifdefs that allow the extern "C" to be seen by the C++ compiler (since __cplusplus is only defined in a C++ compiler), but not by a C compiler (where it not a legal C construct).
|
|||
C++ file |
The following code would be contained in a C++ file and compiled normally.
|
|||
C file |
The following code would be contained in a C file and compiled normally. Note that by including cpp_func.h, a C language function can invoke a C++ language function.
|
|||