OpenEuler 中C与汇编的混合编程

2.5.1用汇编代码编程

将C代码编译成汇编代码
C代码:

/**********a.c file********/
#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);
}

汇编代码

	.file	"a.c"
	.text
	.globl	A
	.type	A, @function
A:
.LFB0:
	.cfi_startproc
	pushl	%ebp
	.cfi_def_cfa_offset 8
	.cfi_offset 5, -8
	movl	%esp, %ebp
	.cfi_def_cfa_register 5
	subl	$24, %esp
	movl	$4, -12(%ebp)
	movl	$5, -16(%ebp)
	movl	$6, -20(%ebp)
	subl	$8, %esp
	pushl	-16(%ebp)
	pushl	-12(%ebp)
	call	B
	addl	$16, %esp
	movl	%eax, -20(%ebp)
	nop
	leave
	.cfi_restore 5
	.cfi_def_cfa 4, 4
	ret
	.cfi_endproc
.LFE0:
	.size	A, .-A
	.ident	"GCC: (Uos 8.3.0.3-3+rebuild) 8.3.0"
	.section	.note.GNU-stack,"",@progbits

2.5.2用汇编语言实现函数

示例2.2

获取CPU寄存器
main.c file:

#include <stdio.h>
extern int get_ebp();
extern int get_esp();
int main()
{
    int ebp, esp;
    ebp = get_ebp();
    esp = get_esp();
    printf("ebp=%8x     esp=%8x\n",ebp,esp);
}

s.s file:

    .section .text
    .global get_esp, get_ebp
get_esp:
    movl    %esp, %eax
    ret
get_ebp:
    movl    %ebp, %eax
    ret


编译运行截图

示例2.3

假设int mysum(int x,int y)返回x和y的和。用汇编语言编写mysum函数。

mysum.s file:

    .text
    .global mysum,printf
mysum:
    pushl %ebp
    movl %esp, %ebp

    movl 8(%ebp), %eax
    addl 12(%ebp), %eax

    movl %ebp, %esp
    pop  %ebp
    ret
    

mysum.c file:

#include <stdio.h>
extern int mysum(int a, int b);
int main()
{
    int a,b,c;
    a = 123; b = 456;
    c = mysum(a,b);
    printf("c = %d\n",c);
}

编译运行截图


2.5.3从汇编中调用C函数

示例2.4:访问全局变量并调用printf()

c file

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

汇编代码:

    .text
    .global sub, a, b, printf
sub:
    pushl   %ebp
    movl    %esp, %ebp

    pushl   b 
    pushl   a 
    pushl   $fmt
    call    printf
    addl    $12, %esp

    movl    %ebp,%esp
    pop     %ebp
    ret

    .data
fmt:    .asciz  "a = %d  b = %d\n"

编译运行截图

posted @ 2021-12-05 11:16  Azraël  阅读(26)  评论(0编辑  收藏  举报