20191218 2021-2022-1-diocs-OpenEuler中C与汇编的混合编程

在X86_64架构下实践2.5中的内容

1. 生成汇编代码
OpenEuler中C与汇编的混合编程
2. 用汇编语言实现函数

  • 获取CPU寄存器
    首先编写hello.c、s.s以及makefile文件,make编译
    OpenEuler中C与汇编的混合编程
    生成hello可执行文件
    OpenEuler中C与汇编的混合编程
    运行结果
    OpenEuler中C与汇编的混合编程
    清理
    OpenEuler中C与汇编的混合编程

  • 用汇编语言编写mysum()函数
    编写mysum.s、main.c和makefile,make编译,运行结果
    OpenEuler中C与汇编的混合编程

  • 从汇编中调用C函数
    首先编写sub.c、main.s、和makefile文件,make编译,运行结果
    OpenEuler中C与汇编的混合编程
    清除
    OpenEuler中C与汇编的混合编程

在OpenEuler(X86_64架构)下实践2.5中的内容

1. 生成汇编代码
OpenEuler中C与汇编的混合编程
汇编代码a.s如下

	.file	"a.c"
	.text
	.globl	A
	.type	A, @function
A:
.LFB0:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	subq	$32, %rsp
	movl	%edi, -20(%rbp)
	movl	%esi, -24(%rbp)
	movl	$4, -4(%rbp)
	movl	$5, -8(%rbp)
	movl	$6, -12(%rbp)
	movl	-8(%rbp), %edx
	movl	-4(%rbp), %eax
	movl	%edx, %esi
	movl	%eax, %edi
	movl	$0, %eax
	call	B
	movl	%eax, -12(%rbp)
	nop
	leave
	.cfi_def_cfa 7, 8
	ret
	.cfi_endproc
.LFE0:
	.size	A, .-A
	.ident	"GCC: (GNU) 7.3.0"
	.section	.note.GNU-stack,"",@progbits

OpenEuler中C与汇编的混合编程

生成汇编代码a.s

	.arch armv8-a
	.file	"a.c"
	.text
	.align	2
	.global	A
	.type	A, %function
A:
.LFB0:
	.cfi_startproc
	stp	x29, x30, [sp, -48]!
	.cfi_def_cfa_offset 48
	.cfi_offset 29, -48
	.cfi_offset 30, -40
	mov	x29, sp
	str	w0, [sp, 28]
	str	w1, [sp, 24]
	mov	w0, 4
	str	w0, [sp, 44]
	mov	w0, 5
	str	w0, [sp, 40]
	mov	w0, 6
	str	w0, [sp, 36]
	ldr	w1, [sp, 40]
	ldr	w0, [sp, 44]
	bl	B
	str	w0, [sp, 36]
	nop
	ldp	x29, x30, [sp], 48
	.cfi_restore 30
	.cfi_restore 29
	.cfi_def_cfa_offset 0
	ret
	.cfi_endproc
.LFE0:
	.size	A, .-A
	.ident	"GCC: (GNU) 10.3.1"
	.section	.note.GNU-stack,"",@progbits

2. 用汇编语言实现函数

  • 编写hello.c、s.s以及makefile
    OpenEuler中C与汇编的混合编程
    OpenEuler中C与汇编的混合编程
    OpenEuler中C与汇编的混合编程
  • 编译运行
    OpenEuler中C与汇编的混合编程

在OpenEuler Raspberry(ARM架构)下实践2.5中的内容(尝试)

1. 生成汇编代码
OpenEuler中C与汇编的混合编程
2. 用汇编语言实现函数

  • 获取CPU寄存器
    首先编写s.s、hello.c和makefile文件
    OpenEuler中C与汇编的混合编程

由于树莓派是基于arm架构,x86中%esp对应SP(R13)寄存器,也就是栈顶寄存器;%ebp对FP(R11)应教材中所提供的是x86_32,于是改写代码hello.c
OpenEuler中C与汇编的混合编程
x86中%eax对应arm中R0,改写代码s.s

参考博客

相关文章:

  • 2021-10-14
  • 2022-12-23
  • 2021-12-17
  • 2022-12-23
  • 2022-02-25
  • 2022-12-23
  • 2021-09-09
  • 2021-05-24
猜你喜欢
  • 2021-07-19
  • 2021-09-18
  • 2021-10-19
  • 2022-12-23
  • 2021-11-26
  • 2022-12-23
相关资源
相似解决方案