Extern "C" is introduced to solve the problem of C ++ function overloading. When designing the C ++ language, the father of C ++ considers the compatibility with C, the introduction of extern "C" enables the use of C library functions without errors in C ++ (most library functions are compiled by C)
During compilation, C and C ++ have different methods to generate modifier names for functions. This can be considered as a mechanism for C ++ to implement function overloading. consider such a section of C code:
int fun(int x){ return 0;}
Use the/Fas option to generate assembly code. Pay attention to the fun function modifier:
; This is the public_fun compiled using C compilation; _ fun is the modifier of function fun _ textsegment_x $ = 8_funproc near; 3: {pushebpmovebp, esp; 4: Return X; moveax, dword ptr _ x $ [EBP]; 5:} popebpret0_funendp_textendsend
The same Code is changed to the C ++ compilation method. The compilation code is as follows:
Public? Fun @ Yahh @ z_textsegment? Fun @ Yahh @ Z proc near ;? Fun @ Yahh @ Z is the modifier of the fun function; 12: {pushebpmovebp, esp; 13: Return 0; xoreax, eax; 14:} popebpret0? Fun @ Yahh @ Z endp; fun_textendsend
It can be seen that the same piece of code, C and C ++ compilation methods are very different, especially when the function is generated to modify the name, so such a program is problematic:
/* fun.c */int fun(int x){ return x;}
// test.cpp#include <stdio.h>extern int fun(int);int main(void){ printf("%d\n", fun(2)); getchar(); return 0;}
The error message is:
The reason is: Fun adopts the C compiling method, and the compiler modifies the name of the function generated by it as _ fun, while in test. the fun function in the CPP file adopts the C ++ compiling method. What is the generated modifier name? Fun @ Yahh @ Z. During the link stage, the redirection fails because the modified names generated by fun are inconsistent!
In order to use the C Compilation Method in C ++, the extern "C" technology is introduced (in fact, this is not the case, think about the library functions used in the project, most of them are compiled in C language. modify the CPP Code:
// test.cpp#include <stdio.h>extern "C"{ extern int fun(int);}int main(void){ printf("%d\n", fun(2)); getchar(); return 0;}
Re-compile, link, and program running is normal!
Add extern "C" outside extern int fun (INT) to declare that the fun function of the compiler is compiled in C language. Therefore, the compiler generates a C-type modifier for the fun function. CPP uses the/Fas option. Pay attention to the modified name of the fun function:
Extrn_fun: near_datasegment $ sg529db '% d', 0ah, 00h_dataends_textsegment_mainproc near; 10: {pushebpmovebp, esppushecx; 11: printf ("% d \ n", fun (2 )); push2call_fun; now the modifier of the fun function is changed to the C method! Addesp, 4 pusheaxpushoffset flat: $ sg529call_printfaddesp, 8