Where do I find the assembly that creates a static variable in the .data section of my C program?

后端 未结 4 668
终归单人心
终归单人心 2021-01-05 21:27

First time poster. 2nd year CS student.

I am exploring the creation of static variables in the .data section of the Virtual Address Space in the context of a C sourc

4条回答
  •  死守一世寂寞
    2021-01-05 21:41

    The initializers for staticVar is stored in the .data section of the executable. Using objdump (e.g. How can I examine contents of a data section of an ELF file on Linux?) should reveal something like this for your file:

    ./test:     file format elf64-x86-64
    
    Contents of section .data:
     00d2c0 00000000 00000000 00000000 00000000  ................
     00d2d0 00000000 00000000 00000000 00000000  ................
     00d2e0 01000000 02000000 03000000 04000000  ................
     00d2f0 05000000 06000000 07000000 08000000  ................
     00d300 09000000 ffffffff 00000000 00000000  ................
     00d310 00000000 00000000 00000000 00000000  ................
    

    That content from the executable is directly mapped into the address space of your process, so there is no need for any code to create the data. Codes that operate on staticVar will refer to the content directly using memory pointers; e.g. for the loop you posted, gcc -S gave me this:

      18                .L5:
      19 0013 90            nop
      20                .L2:
      21 0014 4863C3        movslq  %ebx, %rax
      22 0017 8B148500      movl    staticVar.1707(,%rax,4), %edx
      22      000000
      23 001e 8B45F4        movl    -12(%rbp), %eax
      24 0021 01D0          addl    %edx, %eax
      25 0023 8945F4        movl    %eax, -12(%rbp)
      26 0026 83C301        addl    $1, %ebx
      27 0029 83FB0A        cmpl    $10, %ebx
      28 002c 75E5          jne .L5
    

    Lifetime of this static array would be the lifetime of your process, similar to a global variable. In any case, there is no code that builds it. It's just some data in memory.

    P/S: You may need to add volatile to sum like such: volatile int sum = 0; Otherwise gcc would probably optimize it away since the resulting value of sum is never used.

提交回复
热议问题