Look at the use of the extern keyword in c++ from assembly

  • 2020-04-01 21:38:52
  • OfStack

In c++, the extern keyword is used to declare variables and functions, and when functions are declared, they have the same effect as without extern, that is, the following two statements have the same effect:


extern void fun(); 
void fun(); 

But for variables, there is a difference between having extern and not having extern. When you have extern, you simply tell the compiler that the variable exists, and the compiler does not allocate storage for the variable, which is the actual declaration. Without extern, the compiler allocates storage for the variable at the same time as the declaration.

The following is the c++ source code with extern:


int main() {
    extern int i;
}

The following is the corresponding sink code:

; 1    : int main() {
    push    ebp
    mov    ebp, esp;esp For a register pointing to the top of the stack, always pointing to the top of the stack  ebp It is also a register for giving main Local variables are found on the stack space allocated by the function and are therefore often used as the base address 
                ; The above two sentences save the base address of the previous stack ( The pressure of stack ), And then let the ebp Points 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 push the stack and return the function 

As you can see from the pool code above, no storage space is allocated on the station for variable I

Here is the c++ source code without extern:


int main() {
    int i;
}

The following is the corresponding sink code:

; 1    : int main() {
    push    ebp
    mov    ebp, esp
    push    ecx; And there are extern The biggest difference is this sentence 
               ;ecx It's also a register ecx Is equal to a variable i Storage space is allocated on the stack 
               ; Due to the ecx The value in is uncertain, so if we access a local variable that is 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, without the extern keyword, storage is indeed allocated on the stack for variable I

The above assembly USES cl instructions on the command line, if vs2010 is used to generate the sink code, the sink code may be different, but the meaning is the same.


Related articles: