FAQ 36.03 How can C code call C code?

FAQ 36.03 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 as detailed in the previous FAQ, only this time 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++ code extern "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

The extern "C" declaration causes the C++ compiler to use C calling conventions and name mangling. For example, the C++ compiler might precede the name with a single underscore rather than the usual C++ name-mangling scheme.

The C code then declares the function using the usual C prototype:

 /* This is C code */ void sample(int i, char c, float x); void myCfunction() {   // ...   sample(42, 'a', 3.14);   // ... } 

There can be overloaded C++ functions with the same name as the function that was exported to the C code, but only one of these overloads can be declared as extern "C". Also, the C code cannot access more than one of these since C doesn't support name overloading. Member functions cannot be exported to C code using the extern "C" syntax.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net