在C/C++编程中,我们经常会用到局部变量,笔者想知道在汇编语言中是
如何使用局部变量的,根据《X86汇编语言》中的例子,才弄懂了汇编是如何
分配局部变量。用栈指针减去一个值(需要分配的内存大小)。
代码:
#include <stdio.h>
#include <tchar.h>
extern "C" void CalculateSums_(int a, int b, int c, int *s1, int *s2, int *s3);
int _tmain(int argc, _TCHAR* argv[])
{
int a = 3, b = 5, c = 8;
int s1a, s2a, s3a;
CalculateSums_(a, b, c, &s1a, &s2a, &s3a);
//compute the sums again so we can verify the results
//of CalculateSums_()
int s1b = a + b + c;
int s2b = a * a + b * b + c * c;
int s3b = a * a*a + b * b*b + c * c*c;
printf("Input:a:%4d b:%4d c:%4d\n", a, b, c);
printf("Output:s1a:%4d s2a:%4d s3a:%4d\n", s1a, s2a, s3a);
printf("s1b:%4d s2b:%4d s3b:%4d\n",s1b,s2b,s3b);
return 0;
}
.model flat,c
.code
; extern "C" void CalculateSums_(int a, int b, int c, int* s1, int* s2, int* s3);
;
; Description: This function demonstrates a complete assembly
; language prolog and epilog.
;
; Returns: None.
;
; Computes: *s1 = a + b + c
; *s2 = a * a + b * b + c * c
; *s3 = a * a * a + b * b * b + c * c * c
CalculateSums_ proc
;Function prolog
push ebp
mov ebp,esp
sub esp,12 ;Allocate local storage space
push ebx
push esi
push edi
;Load arguments
mov eax,[ebp+8] ;eax="a"
mov ebx,[ebp+12] ;ebx='b'
mov ecx,[ebp+16] ;ecx='c'
mov edx,[ebp+20] ;edx='s1'
mov esi,[ebp+24] ;esi='s2'
mov edi,[ebp+28] ;edi='s3'
;Compute 's1'
mov [ebp-12],eax
add [ebp-12],ebx
add [ebp-12],ecx ;final 's1' result
;Compute 's2'
imul eax,eax
imul ebx,ebx
imul ecx,ecx
mov [ebp-8],eax
add [ebp-8],ebx
add [ebp-8],ecx ;final 's2' result
;Compute 's3'
imul eax,[ebp+8]
imul ebx,[ebp+12]
imul ecx,[ebp+16]
mov [ebp-4],eax
add [ebp-4],ebx
add [ebp-4],ecx ;final 's3' result
;Save 's1','s2','s3'
mov eax,[ebp-12]
mov [edx],eax ;save 's1'
mov eax,[ebp-8]
mov [esi],eax ;save 's2'
mov eax,[ebp-4]
mov [edi],eax ;save 's3'
;Function epilog
pop edi
pop esi
pop ebx
mov esp,ebp
pop ebp
ret
CalculateSums_ endp
end
在vs2017上的运行效果: