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中