FAQ 36.02 How can C code call C code?

FAQ 36.02 How can C++ code call C code?

The C++ compiler must know that the function has C linkage.

If the C code that is being called is part of the standard C library, such as printf(), simply #include the correct C header file and call the function.

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" } 

If a C header file needs to be included in a lot of C++ locations, the extern "C" part can be moved into the header file, provided only the C++ compiler sees it. The simplest way to do this is to create a new C++ header file that includes the C header file. For example, if "Fred.h" is a C header file, "Fred.hpp" can be created as a C++ header file:

 // Fred.hpp extern "C" {   #include "Fred.h"                                  <-- 1 } 

(1) Include the C header file

The other approach is to modify the C header file directly, which obviously can only be done if the team has control over the C header file. 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 __cplusplus   extern "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.



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