以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
首先看sum函數有兩個參數,所以main函數中 pushl -12(%ebp) pushl -8(%ebp) 傳入了兩個參數。參數傳遞完成後執行call sum調用sum函數。調用完成後,執行addl $8,%esp 清理棧幀。由於sum函數返回值爲int型,所以執行movl %eax,-4(%ebp)將返回值傳入給main函數的a變量。
另外如果參數爲char ,short,unsigned char ,unsigned short 類型,它們將擴張爲int 類型,傳入。
返回參數可以是char,short,unsigned char ,unsigned short 類型。
char lower(char a)
{
return a+32;
}
int main(void)
{
char a='A';
char b;
b=lower(a);
return 0;
}
main函數
.text
.global main
main:
pushl %ebp
movl %esp,%ebp
subl $2,%esp
movl $'A',-1(%ebp)
movsbl -1(%ebp),%eax
pushl %eax
call lower
addl $4,%esp
movb %al,-1(%ebp)
movl $0,%eax
leave
ret
lower函數
.text
.global lower
lower:
pushl %ebp
movl %esp,%ebp
movl 8(%ebp),%eax
movsbl %al,%eax
addl $32,%eax
leave
ret
從代碼中可以發現調用的函數,如果有參數,則第一個參數在8(%ebp)處,第二個在12(%ebp)中,以此類推。
返回值一般放入%eax中。如果返回值是char,則只用%al,如果返回值是short,則只用%ax。