In c ++, the extern keyword is used to declare variables and functions. When declaring a function, it has the same effect as that without extern. That is, the following two statements have the same effect:
Copy codeThe Code is as follows: extern void fun ();
Void fun ();
However, for variables, there is a difference between extern and extern. When extern exists, the compiler only informs the compiler that the variable exists. The Compiler does not allocate storage space for the variable, that is, the real declaration; if no extern exists, the compiler also allocates storage space for the variable while declaring it.
The following is the c ++ source code when there is extern:
Copy codeThe Code is as follows: int main (){
Extern int I;
}
The following is the corresponding assembly code:
Copy codeThe Code is as follows:; 1: int main (){
Push ebp
Mov ebp, esp; esp is a register pointing to the top of the stack. It always points to the top of the stack. ebp is also a register used to search for local variables in the stack space allocated to the main function, therefore, it is often used as a base address.
The role of the above two statements is to save the base address of the previous stack (press the stack), then let the ebp point to the stack space of the current function, and then serve as the base address again
; 2: extern int I;
; 3 :}
Xor eax, eax
Pop ebp
Ret 0; these three statements are used for Stack rollback and function return.
From the assembly code above, we can see that no storage space is allocated for variable I on the station.
The following is the c ++ source code without extern:
Copy codeThe Code is as follows: int main (){
Int I;
}
The following is the corresponding assembly code:
Copy codeThe Code is as follows:; 1: int main (){
Push ebp
Mov ebp, esp
Push ecx; the biggest difference with the extern clause is
Ecx is also a register. Here we talk about the value pressure stack of ecx, which is equivalent to allocating storage space on the stack for variable I.
Because the values in ecx are uncertain, If we access a local variable without initialization, we often get a strange value.
; 2: int I;
; 3 :}
Xor eax, eax
Mov esp, ebp
Pop ebp
Ret 0
It can be seen that, without the extern keyword, the storage space is indeed allocated for variable I on the stack.
The above assembly is generated using the cl command in the command line. If vs2010 is used to generate the assembly code, the assembly code may be different, but the meaning is the same.