In C + +, the extern keyword is used to declare variables and functions, and when declaring functions, there is an effect like no extern, that is, the following two statements have the same effect:
Copy Code code as follows:
extern void Fun ();
void Fun ();
But for variables, there is a difference between and without extern, and when there is an extern, just tell the compiler that there is this variable, the compiler does not allocate storage space for the variable, that is, a true declaration; if there is no extern, then the compiler also allocates storage space for the variable when it is declared.
Here is the C + + source code when there is an extern situation:
Copy Code code as follows:
int main () {
extern int i;
}
the following is the corresponding assembly code:
Copy Code code as follows:
; 1:int Main () {
Push EBP
mov ebp, ESP;ESP is a register pointing to the top of the stack, always pointing to the top of the stack EBP is also a register, used in the stack space allocated to the main function to search for local variables, so often as a base
The above two sentences are used to save the base address of the previous stack (press stack), then let Ebp point to the stack space of the current function, again as the base address
; 2:extern int i;
; 3:}
xor eax, EAX
Pop EBP
RET 0; These three sentences are used to retire the stack, and the return of the function
As can be seen from the above assembly code, there is no storage space allocated for the variable I on the station.
Here is the C + + source without the extern situation:
Copy Code code as follows:
the following is the corresponding assembly code:
Copy Code code as follows:
; 1:int Main () {
Push EBP
MOV EBP, esp
push ecx; The biggest difference from having an extern is this sentence.
ECX is also a register, which speaks of the value of the ECX stack, equivalent to the variable i on the stack allocated storage space
Because the value in ECX is uncertain, so if we access local variables that are not initialized, we often get a strange value
; 2:int i;
; 3:}
xor eax, EAX
mov esp, EBP
Pop EBP
RET 0
As you can see, when there is no extern keyword, you do allocate storage space on the stack for the variable i
The above assembly is generated using the CL instruction on the command line, and if the vs2010 is used to generate the sink code, the sink code may be different, but the meaning is the same.