top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Explain how to call C code from C++ code. Explain with an example?

+5 votes
594 views
Explain how to call C code from C++ code. Explain with an example?
posted Mar 5, 2015 by Emran

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes

To call a C program in C++ , the basic requirement is both the compilers and runtime libraries must be compatible. They must define the primitive data types such as int, float, char etc.

Accessing C Code From Within C++ Source:

A linkage specification is provided by C++, which is used to declare a function that follows the program linkage conventions for a supported language. C++ compilers support C linkage for compatible C compilers.

To access a function with C linkage, the function need to be declared to have C linkge.

The following code snippet depicts the linkage declaration:

extern "C" {
          void f(); // C linkage
          extern "C++" {
                  void g(); // C++ linkage
                  extern "C" void h(); // C linkage
                  void g2(); // C++ linkage
          }
          extern "C++" void k();// C++ linkage
                     void m(); // C linkage
}

The following code snippet depicts the inclusion of a c header file.

extern "C" 
{
       #include "header.h"
}
answer Mar 6, 2015 by Mohammed Hussain
0 votes

In order to call a function defined as C function in C++ code, extern "C" is used.
extern "C" void foo( );

void main()
{
// the function call:
foo( );
}
foo function is defined somewhere else in .c file.

answer Mar 6, 2015 by Vikram Singh
...