Tuesday, August 24, 2010

C in C++ Code and C++ code in C

extern "C" is understandable by only C++ compiler thats why we generaly wrap it in  # if defs . When same code can be compiled by c compiler also 
only cpp compiler has defined cpluscplus.


#ifdef __cplusplus
 extern "C" {
 #endif



In cpp code if we want a function that will be callable from C program.We need declaration like this
cpp file.

#include 

extern "C" void hello() {
    std::cout << "hello" << '\n';
}

A function declared as extern "C" uses the function name as symbol name, just as a C function. For that reason, only non-member functions can be declared as extern "C", and they cannot be overloaded.
C++ compiler uses a technique termed name mangling which incorporates the function name with its signature (list of arguments) in order to create a unique name for it, even in case of overloading (this technique is used both for external function and class member functions).
In order to enforce the compiler to avoid name mangling, a global function has to be declared as extern "C":
extern "C" void f(int); //now the generated name is identical to the one given by the programmer.

How to include non standard C header file in C++ code?
 //C++ code

 extern "C" {
   
// Get declaration for f(int i, char c)
   #include "my-C-code.h"
 }

 int main()
 {
   f(7, 'a');  

   
...
 } 


To make it easier its better to change header file itself .
at top putting
#ifdef __cplusplus
 extern "C" {
 #endif

At end  put
 #ifdef __cplusplus
 }
 #endif


Now it  .h can be included  in cPP simply 
 
 // Get declaration for f(int i, char c, float x)
 #include "my-C-code.h" 


 int main()
 {
   f(7, 'x');     

   
...
 }

--------------
if we dont want to include whole file individual function can be declared 
extern "C" void f(int i, char c); 
Or a group can be :

extern "C" {
   void   f(int i, char c);
   int    f2(char* s, char const* s2);
   double f3(double a, double b);
 }

Followers