## Sunday, January 27, 2008

### How can C++ code call C code?

If the C code that is being called is not part of the standard C library, the C++ compiler needs to know that the function is a C function. To do this, include an extern "C" block in the C++ code, and declare the C function inside the block:

extern "C" {void myCfunction(int x, int y);void yourCfunction(float z);}

An entire C header file can be included within an extern "C" block:
extern "C" {#include "my-C-header.h"#include "your-C-header.h"}
The other approach is to modify the C header file directly. The extern "C" part is wrapped in an #ifdef to make sure these lines are seen only by C++ compilers, not by C compilers. The idea is simple: insert the following lines near the top of the C header file.
#ifdef __cplusplusextern "C" {#endif
Then insert the following near the bottom of the C header file.
#ifdef __cplusplus}#endif
This works because the C++ compiler automatically #defines the preprocessor symbol __cplusplus.

### How can C code call C++ code?

The C++ compiler must be told to compile the C++ function using C-compatible calling conventions (also known as C linkage). This is done using the same extern "C" construct， the extern "C" goes around the declaration of the C++ function rather than the declaration of the C function. The C++ function is then defined just like any other C++ function:

// This is C++ codeextern "C" { void sample(int i, char c, float x) throw();}void sample(int i, char c, float x) throw(){                                                    <-- 1}

(1) The C++ code that defines the function goes here