以sum函數爲例
int sum(int a,int b)
{
return a+b;
}
它的彙編代碼
.text
.global sum
sum:
pushl %ebp
movl %esp,%ebp
movl 8(%ebp),%eax
addl 12(%ebp),%eax
leave
ret
然後是main函數
int main(void)
{
int a;
int b=12;
int c=24;
a=sum(b,c);
return 0;
}
彙編代碼爲
.text
.global main
main:
pushl %ebp
movl %esp,%ebp
subl $12,%esp
movl $12,-8(%ebp)
movl $24,-12(%ebp)
pushl -12(%ebp)
pushl -8(%ebp)
call sum
addl $8,%esp
movl %eax,-4(%ebp)
movl $0,%eax
leave
ret
申請局部變量是用subl $12,%esp 在棧上申請了12字節的空間保存a,b,c。a爲-4(%ebp),b爲-8(%ebp),以此類推。
寄存器使用慣例
根據慣例,寄存器%eax,%edx,%ecx被劃分爲調用者保存寄存器。當過程p調用q時,q可以覆蓋這些寄存器,而不會破壞任何p所需的數據。另一方面,寄存器%ebx,%esi,%edi被劃分爲調用者保存寄存器。這意味着q必須在覆蓋這些寄存器的值之前,先把它們保存進棧中,並在返回前恢復它們,應爲p可能會在今後的計算中需要這些值。