以下代碼示范交換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\n", a); printf("%d\n", b); return 0; }
.section .data a: .int 534 b: .int 1057 format: .asciz "%d\n" .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