GCC的組合語言用的是AT&T的文法。
源檔案:test.c
#include <stdio.h>
#include <fcntl.h>
int swap(int *a, int *b)
{
int c ;
c = *a;
*a = *b;
*b = c;
return c;
}
int main(int argc, char *argv[])
{
int a, b, c;
a = 16; b = 32;
c = swap(&a, &b);
return 1;
}
彙編結果: gcc -S test.c
.file "test.c"
.text
.align 2
.globl swap
.type swap,@function
swap:
pushl %ebp
movl %esp, %ebp
subl $4, %esp 為整型局部變數c 在棧中分配空間
movl 8(%ebp), %eax 取第一個參數a
movl (%eax), %eax 取a地址裡的內容 *a
movl %eax, -4(%ebp) 儲存到局部變數c中
movl 8(%ebp), %edx 取第一個參數a
movl 12(%ebp), %eax 取第二個參數 b
movl (%eax), %eax 儲存*b
movl %eax, (%edx) 將*b 儲存到 a的地址裡(*a)
movl 12(%ebp), %edx 再去參數b
movl -4(%ebp), %eax 將局部變數c的值(先已經是a的值)取出
movl %eax, (%edx) 將這個指儲存到b的地址裡(*a)
movl -4(%ebp), %eax 傳回值c儲存在eax中
leave 等同於 movl %ebp, %esp; popl %ebp;
ret
.Lfe1:
.size swap,.Lfe1-swap
.align 2
.globl main
.type main,@function
main:
pushl %ebp
movl %esp, %ebp
subl $24, %esp
andl $-16, %esp
movl $0, %eax
subl %eax, %esp
movl $16, -4(%ebp)
movl $32, -8(%ebp)
subl $8, %esp
leal -8(%ebp), %eax
pushl %eax
leal -4(%ebp), %eax
pushl %eax
call swap
addl $16, %esp
movl %eax, -12(%ebp) 將swap的傳回值(在eax中),放到局部變數c中
movl $1, %eax 將eax賦值為傳回值 1
leave
ret
.Lfe2:
.size main,.Lfe2-main
.ident "GCC: (GNU) 3.2 20020903 (Red Hat Linux 8.0 3.2-7)"
8(%ebp)是第一個參數 12(%ebp)是第二個參數
-4(%ebp)是第一個局部變數
函數傳回值 儲存在eax中