SilverScreen Solid Modeler

Calling C++ from C

Calling C++ from C

Previous topic Next topic  

Calling C++ from C

Previous topic Next topic JavaScript is required for the print function  

SilverPlusEllipse

 

Calling C++ from C

 


Occasionally you will find yourself in a position, particularly if you are porting older C code, where it would be convenient, if not necessary, to call a C++ routine from C code. A legal and portable way to do this is to define a C++ function with a C interface (note that this must be a global function, and not a member function). Such a function is defined in a .cpp file (C++ source) and declared using the extern "C" mechanism. This makes the function appear to be C-callable, but inside the function, you may make use of any C++ constructs that you wish. The function may only take C-style parameters (no classes, class pointers, references, etc.).

 

For example, suppose that you wish to call C++ function cpp_func from a .C file (C source). Then the technique is to define the function in a C++ file, but declare it in such a way that it has “C” interface. The following is an example:

 

 

Header file

The following code could be placed in an include file, or header file, to declare your C++ function with a "C" interface. Note how the extern "C" mechanism is wrapped by ifdefs that allow the extern "C" to be seen by the C++ compiler (since __cplusplus is only defined in a C++ compiler), but not by a C compiler (where it not a legal C construct).

 

 

C / C++ Code

 

 //

 // cpp_func.h: Declares a C++ function so it is C-callable

 //

 

 #if defined(__cplusplus)

 extern "C"

    {

 #endif

 

    int cpp_func( void )

 

 #if defined(__cplusplus)

    }

 #endif

 

 

 

C++ file

The following code would be contained in a C++ file and compiled normally.

C / C++ Code

 

  //

  // cpp_func.cpp: A C++ function body, whose declaration is contained

  //               in cpp_func.h

  //

 

  #include "cpp_func.h"

  . . .

  int cpp_func( void )

     {

     // Perform C++ work here, if desired

 

     return some_integer_value;

     }

 

 

 

C file

The following code would be contained in a C file and compiled normally. Note that by including cpp_func.h, a C language function can invoke a C++ language function.

C / C++ Code

 

  //

  // c_func.c: A C function body that calls a C++ function

  //

 

  #include "cpp_func.h"

 

  . . .

 

  int c_func(void)

     {

     int rval;

 

     rval = cpp_func();

 

     return rval;

     }