以下代码示范交换a和b两个整数的函数,编译环境Ubuntu14.04(32位)
假如要实现以下C代码
#include <stdio.h> void swap(int *xp, int *yp) { int x = *xp; int y = *yp; *xp = y; *yp = x; } int main() { int a = 534, b = 1057; swap(&a, &b); printf("%d ", a); printf("%d ", b); return 0; }
- 汇编代码如下:
.section .data a: .int 534 b: .int 1057 format: .asciz "%d " .section .text .global _start _start: pushl %ebp movl %esp, %ebp subl $24, %esp #给栈分配内存24字节保存局部变量 movl $a, %eax movl %eax, 4(%esp) movl $b, %eax movl %eax, (%esp) call swap #调用swap函数 pushl a #打印a pushl $format call printf pushl b #打印b pushl $format call printf movl $0, (%esp) call exit swap: pushl %ebp #保存调用前栈帧地址 movl %esp, %ebp pushl %ebx #根据习惯,保存寄存器ebx movl 8(%ebp), %edx #get xp movl 12(%ebp), %ecx #get yp movl (%edx), %ebx #get x movl (%ecx), %eax #get y movl %eax, (%edx) movl %ebx, (%ecx) popl %ebx popl %ebp ret
- 编译
as swap.s -o swap.o
- 链接
ld -lc -I /lib/ld-linux.so.2 swap.o -o swap
- 执行
./swap