Function: Mixed Programming of C and C ++.
Principle: After the C and C ++ compilers compile, the function name will be compiled into different names. The target cannot be found in the Link stage name search, which will be explained in the following examples.
Usage: ①. Function defined in file C ,. when the CPP file is to be called. use extern "c" to declare the function in the CPP file; ② reverse ,. functions defined in the CPP file ,. to call the c file. use extern "c" to declare in the CPP file ,. the C file only uses the normal extern declaration.
The two source files are compiled into. O files respectively, and then linked to the execution file. You must use g ++ to generate an execution file by linking the. o file.
Instance:
Declared in the source file,No HeaderFile
Function defined in the. c file, called in the. cpp file:
1 //. function 2 extern int myadd (int A, int B) defined in file C; 3 4 int myadd (int A, int B) 5 {6 Return A + B; 7}
1 //. CPP file call 2 # include <iostream> 3 using namespace STD; 4 5 extern "C" int myadd (int A, int B); 6 7 int main () 8 {9 cout <myadd (3, 7) <Endl; 10 return 0; 11}
Function defined in the. cpp file, called in the. c file:
1 //. the CPP file defines the function 2 extern "C" int myadd (int A, int B); 3 4 int myadd (int A, int B) 5 {6 Return A + B; 7}
1 //. c file call 2 # include <stdio. h> 3 4 extern int myadd (int A, int B); 5 6 int main () 7 {8 printf ("% d \ n", myadd (3, 7); 9 return 0; 10}
IfDeclare in header file, The. c file normally contains this header file, and the. cpp file should be used
1 //. cpp File Inclusion Method 2 extern "C" 3 {4 # include "myhead. H" 5}
To include the header file. All the functions declared in this header file are compiled in C mode.
Principle supplement: In the c file, the name of the previously compiled function is similar to _ myadd. After CPP is compiled, the name of the function is similar to _ myadd_int_int, because CPP must support overloading, this method is used to distinguish between overloaded functions.
Function of extern "C"