Analysis of extern 'C' in C and C++

  • 2020-04-02 02:42:49
  • OfStack

We often see extern "C" in C/C++ programs, which is an important concept. This article will illustrate the role of extern "C" in C/C++ as an example. Share with you for your reference. Specific analysis is as follows:

Function: Achieve C and C++ mixed programming.

Principle: After the C and C++ compilers compile, the function names are compiled into different names, and the link stage name lookup fails to find the target, which will be explained in the following examples.

Usage:
(1) when the function defined in c file is called by the.cpp file, the function is declared with extern "c" in the CPP file.
On the other hand, functions defined in.cpp files that are called by.c files are also declared with extern "c" in.cpp files.

The two source files are compiled into.o files and linked into execution files. You must use g++ when linking to.o files to generate execution files.

Example:

There is no header file declared in the source file

Function defined by. C file, called by. CPP file:


//Function defined in the.c file
extern int myadd(int a, int b);
int myadd(int a, int b)
{
  return a+b;
}


//Call to the.cpp file
#include <iostream>
using namespace std;
extern "C" int myadd(int a, int b);
int main()
{
  cout << myadd(3, 7) << endl;
  return 0;
}

Function defined by. CPP file, called by. C file:


//The function defined in the.cpp file
extern "C" int myadd(int a, int b);
int myadd(int a, int b)
{
  return a + b;
}


//Call to the.c file
#include <stdio.h>
extern int myadd(int a, int b);
int main()
{
  printf("%dn", myadd(3, 7));
  return 0;
}

If declared in a header file, the.c file normally contains the header file, and the.cpp file should be used


//. How the CPP file is included
extern "C"
{
  #include "myHead.h"
}

Contains a header file in which declared functions are compiled in C mode.

Principle supplement: in the C file, the compiled function of the above function is named similar to the form _myadd, while the compiled function of CPP is named similar to the form _myadd_int_int, because CPP supports overloading in this way to distinguish the overloaded function.

I believe that this article has a certain reference value for everyone's C++ programming.


Related articles: