2.5 OpenEuler 中C与汇编的混合编程(选做)待完善

a.c

#include <stdio.h>
extern int B();
int A(int x,int y)
{
int d, e,f;
d = 4; 
e = 5;
f= 6;
f = B(d,e);
}


a.s

.text
 .globl A
A:
 pushl  %ebp
 movl  %esp,%ebp

 subl  $24, %esp
 movl  $4,-12(%ebp)      # d=4
 movl  $5,-8(%ebp)       # e=5
 movl  $6, -4(%ebp)      # f=6

 subl  $8,%esp
 pushl  -8(%ebp)         # push e
 pushl  -12(%ebp)        # push d
 call  B
 addl  $16,, %esp        #clean stack
 movl  %eax,-4(%ebp)     # f=return value in AX
 leave
 ret

2(1)

s.s

        .global get_esp,get_ebp
get_esp:
        movl  %esp,%eax
        ret
get_ebp:
        movl  %ebp,%eax
        ret
#====================================
int main()
{
  int ebp,esp;
  ebp = get_ebp();
  esp = get_esp();
  printf("ebp=%8x  esp=%8x\n",ebp,esp);
}

2(2)

sum.c

int main() # driver program to test mysum() function
{
  int a,b,c;
  a = 123; b = 456;
  c = mysum(a, b);
  printf("c=%d\n", c);     // c should be 579
}

mysum.s

        .text
        .global mysum,printf
mysum:
        pushl %ebp
        movl %esp,ebp
        movl 8(%ebp),eax
        add1 12(%ebp),%eax
        movl %ebp,%esp
        pop %ebp
        ret

3

sub.c

#include <stdio.h>
int a,b;
int main()
{
  a = 100; b = 200;
  sub();
}

Assembly Code

        .text
        .global sub, a, b, printf
sub:
        pushl  %ebp
        movl   %esp,%ebp
        pushl  b
        pushl  a
        pushl  $fmt        # push VALUE (address) of fmt
        call   printf      # printf(fmt,a,b);
        addl   $12, %esp
        movl   %ebp,%esp
        popl   %ebp
        ret
        .data
fmt:   .asciz   "a=%d b=%d\n"

汇编代码最好自己打,或者复制后将所有间隔改为缩进(Tab),否则编译错误

posted @ 2021-11-27 11:45  氧气2019  阅读(17)  评论(0编辑  收藏  举报