The intent of extern "C" in C + + is to implement mixed programming between C + + and C and other languages.
C + + supports function overloading, whereas programming language C is not supported. Functions are compiled in C + + with different names in the symbol library than in the C language.
For example, suppose a function is prototyped as: void int int y) The function is compiled by the C compiler and is named _foo in the symbol library.
The C+ + compiler produces names like _foo_int_int (different compilers may generate different names, but all use the same mechanism, and the resulting new name is called "Mangled Name").
1. If you want to invoke the C language function in C + + program, use extern "C" in C + + program to modify the C program to be called , tell the C + + compiler that this function is written in C, is generated by C language compiler, when calling him please follow the C language habit to pass parameters and so on. Examples are as follows:
First, we have a C-language library of functions: LIBMYCLIB.A (reference gcc to generate static and dynamic libraries) [1]
Gcc-c clib_hello.c clib_math.c
Ar-r LIBMYCLIB.A *.O
//clib_hello.c#include <stdio.h>voidSayHello (void) {printf ("clib hello!\n");}//clib_math.cintAddintVaintvb) { returnva+vb;}//clib_hello.hextern voidSayHello (void);//clib_math.hextern intAddintVaintVB);
Then, CPP compiles the link C function library
g++ cppMain.cpp Libmyclib.a-o Democpp
//CppMain.cpp#include<iostream>using namespacestd;#if0extern "C"{////Yes, but not recommended. "Huawei Technology Co., Ltd. C language Programming code" rule 1.8 prohibits the inclusion of header files in extern "C". #include"clib_hello.h"#include"clib_math.h"}#endifextern "C" voidSayHello (void);extern "C" intAddintVaintvb);//extern void SayHello (void);//extern int Add (int va, int vb);//compile error, undefined reference to ' xxx () 'intMain () {inti = Add (2,3); cout<<"2+3="<<i<<Endl; SayHello (); return 0;}
Why do standard header files have a structure similar to the following?
#ifdef __cplusplus extern " C " {#endif//.... Header file body part void cfree (); int Malloc_trim (); // .... #ifdef __cplusplus}; /* */#endif
This structure ensures that the header file can be used by CPP or C programs,
If #ifdef __cplusplus, the header file body becomes extern "C" {...}, guaranteed to be used by CPP.
If #ifndef __cplusplus, the header file body is ..., guaranteed to be used by C.
There are also ways to do this:
#ifdef __cplusplus #define Cpp_asmlinkage extern "C"#else#define cpp_asmlinkage#endif#define Asmlinkage cpp_asmlinkagevoid Resume (voidvoid free (void );....
Reference:
1. GCC generates static and dynamic libraries http://blog.chinaunix.net/uid-17267213-id-3057974.html
2. extern "C" usage parsing http://www.cnblogs.com/rollenholt/archive/2012/03/20/2409046.html
How to call C + + functions in 3.C http://www.cppblog.com/franksunny/archive/2007/11/29/37510.html
C++,extern "C"