top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

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

+5 votes
114 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
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...