[英]Why assembly code is different for simple C program with different gcc version?
[英]Assembly version of c program on gcc version 4.6.3
我用C語言編寫了一個小數組程序
#include <stdio.h>
int main()
{
int arr[]={1,2,3,4,5};//int size is 4, elements 5 so size of array = 4*5 = 20
printf("%d\n", sizeof(arr));
return 0;
}
我用
gcc -O2 -fverbose-asm -S -c arr_n_pointer_confusion.c
我懂了,
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "%d\n"
.section .text.startup,"ax",@progbits
.p2align 4,,15
.globl main
.type main, @function
main:
.LFB22:
.cfi_startproc
pushl %ebp #
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp #,
.cfi_def_cfa_register 5
andl $-16, %esp #,
subl $16, %esp #,
movl $20, 8(%esp) #,
movl $.LC0, 4(%esp) #,
movl $1, (%esp) #,
call __printf_chk #
xorl %eax, %eax #
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE22:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
.section .note.GNU-stack,"",@progbits
任何人都可以將C中的匯編步驟聯系起來。為什么我要這樣做是為了稍微了解匯編代碼,以便我可以理解指針與數組之間的區別。
基本上,因為編譯器在編譯時就知道該數組的內容,所以它可以刪除該數組,而只需將sizeof(array)
替換為20,而不必在運行時實際初始化該數組。
.cfi_startproc
pushl %ebp # Save the value of ebp (points to the base of the stack) in the stack
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp #, Set the value of the base of the stack to the top of it
.cfi_def_cfa_register 5
andl $-16, %esp # Align the stack with a 16-byte boundary, used for SIMD instructions
subl $16, %esp # Subtract 16 from the value of the stack pointer (reserving 16 bytes of space for the stack)
movl $20, 8(%esp) # Set the memory 8 bytes above the stack as '20'
movl $.LC0, 4(%esp) # Move the string "%d\n" 4 bytes above the stack
movl $1, (%esp) # Set the flag for __printf_chk() to 1, enabling stack overflow checks
call __printf_chk # Print our string
xorl %eax, %eax # Zero out the eax register (i.e. store the return code in eax, which is 0)
。 因此,傳遞給__printf_chk的參數為(1, "%d\\n", 20)
。
使用gcc -g -fverbose-asm -S arr_n_pointer_confusion.c
。 然后,編譯器將添加.loc
偽語句,這些偽語句引用源文件中的行號。 然后,您可以輕松地將匯編程序源與C代碼相關聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.