Calling C functions in your C++ code
Have you ever wanted to call a c function located in one file within a different c++ (.mm / .cpp) file?
If you did, you probably know that it can be a royal pain if you don’t know the trick.
So if like me you’ve been looking for the solution, it’s very easy! Just use the extern “C” keyword (not to be confused with plain extern). Here’s an example:
extern "C" #include "my_c_code.h";
This also works with the Objective-C #import keyword:
extern "C" #import "MyObjCClass.h";
or alternatively for multiple includes
extern "C" {
#include "my_c_code.h"
#include "my_other_c_code.h"
}
And that’s the way you include someone else’s C code into your C++ files. Easy!
But…
If you’re writing brand new C code and you want it to be automatically compatible with other C++ code you can build it in a way that will make it #include’able into any source file.
Using the __cplusplus preprocessor variable you can check if the current build target is a c++ file and if so, surround your code with extern “C”
So for example let’s say this is our current C header file:
//my_c_header.h: int addOne(int n); int globalVar; //..etc
To make this code C++ friendly, we’d do this:
//my_cpp_friendly_c_header.h:
#ifdef __cplusplus
extern "C" {
#endif
int addOne(int n);
int globalVar;
//..etc
#ifdef __cplusplus
}
#endif
Now in your C++ file you can just write
// my_cpp_code.cpp #include "my_cpp_friendly_c_header.h"
So if you know that your C code will be included into C++ source, it’s always a good idea to wrap it in extern “C” { … } to avoid headaches later on…
More info over at: http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html


