From the assembly of c++ function inside the use of the static keyword

  • 2020-04-01 21:39:00
  • OfStack

Here's how it works from assembly language.

Here is the c++ source code:


void add() {
    static int i = 1;
    i++;
}
int main() {
   add();

}

The following is the sink code corresponding to main

; 5    : int main() {
    push    ebp
    mov    ebp, esp
; 6    :    add();
    call    ?add@@YAXXZ                ;  call add
; 7    :    
; 8    : }
    xor    eax, eax
    pop    ebp
    ret    0

The following is the assembly code corresponding to the add function:

; 1    : void add() {
    push    ebp
    mov    ebp, esp
; 2    :     static int i = 1;
; 3    :     i++;
    mov    eax, DWORD PTR ?i@?1??add@@YAXXZ@4HA; Take a variable i The value of the 
    add    eax, 1; Perform addition 
    mov    DWORD PTR ?i@?1??add@@YAXXZ@4HA, eax; Save variable i The value of the 
; 4    : }
    pop    ebp
    ret    0

As you can see, both the main function and the add function, we don't see the allocation of storage space for I, that is, I is not in their call stack.

Now look at the following sink code:


_DATA    SEGMENT
?i@?1??add@@YAXXZ@4HA DD 01H                ;  As a variable i Declare storage space 
; Function compile flags: /Odtp
_DATA    ENDS

This statement pre-allocates storage space for I and defines it outside of the above two function pool encodings. Therefore, the variable lifetime inside the function decorated with the static keyword exists in the entire program, but the visibility is still only inside the add function, not outside.


Related articles: