汇编程序中引用头文件

本文详细介绍了在x86和AT&T风格以及ARM汇编语言中,如何使用头文件和预处理器(如cpp)来编译HelloWorld程序,并展示了Makefile和test.h的用法。重点在于预处理步骤对汇编源文件的影响和实际运行结果。
摘要由CSDN通过智能技术生成

写在前面

汇编程序中也是可以使用头文件的,因为头文件实际上就是预处理中的一环,使用预处理器也对汇编程序中的头文件进行预处理
本文使用的汇编例程:
x86版 AT&T汇编hello world
ARM版 ARM汇编hello world

x86汇编示例(AT&T风格

#include"test.h"
.data
	strr:   .string  hellostr
	len = .-strr
.text
	.global _start
_start:
	movq    $1,    %rax    # syscall number of write
	movq    $1,    %rdi    # param1: stdout
	movq    $strr, %rsi    # param2: str address
	movq    $len,  %rdx    # param3: out length
	syscall

	movq    $60,   %rax    # syscall number of exit
	syscall

test.h内容如下:

#define hellostr "hello world~\n"

Makefile内容如下:

AS=as
LD=ld

all: test.o
	$(LD) test.o -o test
test.o: test.s
	$(AS) test.s -o test.o
test.s: oritest.s
	cpp oritest.s -o test.s
clean:
	rm *.o rm test

关键就在于make test.s这一步,使用gnu的预处理器cpp对oritest.s进行预处理得到test.s
直接使用汇编器as编译oritest.s会失败


预处理后的test.s内容如下:

# 1 "oritest.s"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "oritest.s"
# 1 "test.h" 1
# 2 "oritest.s" 2
.data
 strr: .string "hello world~\n"
 len = .-strr
.text
 .global _start
_start:
 movq $1, %rax # syscall number of write
 movq $1, %rdi # param1: stdout
 movq $strr, %rsi # param2: str address
 movq $len, %rdx # param3: out length
 syscall

 movq $60, %rax # syscall number of exit
 syscall


ARM汇编示例

汇编源文件:oritest.s
hellostr在同级目录下的test.h中定义

#include"test.h"
.data
	strr:   .string hellostr
	len = .-strr
.text
	.global _start
_start:
	// write syscall
	mov     x8,     #64     
	mov     x0,     #1      // stdout
	ldr     x1,     =strr
	mov     x2,     len
	svc     #0			

	// exit syscall
	mov     x8,     #93
	svc     #0

test.h内容如下:

#define hellostr "hello world~\n"

Makefile内容如下:

AS=as
LD=ld

all: test.o
	$(LD) test.o -o test
test.o: test.s
	$(AS) test.s -o test.o
test.s: oritest.s
	cpp oritest.s -o test.s
clean:
	rm *.o rm test

关键就在于make test.s这一步,使用gnu的预处理器cpp对oritest.s进行预处理得到test.s
直接使用汇编器as编译oritest.s会失败


预处理后的test.s内容如下:

# 0 "oritest.s"
# 0 "<built-in>"
# 0 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 0 "<command-line>" 2
# 1 "oritest.s"
# 1 "test.h" 1
# 2 "oritest.s" 2
.data
 strr: .string "hello world~\n"
 len = .-strr
.text
 .global _start
_start:

 mov x8, #64
 mov x0, #1
 ldr x1, =strr
 mov x2, len
 svc #0


 mov x8, #93
 svc #0

运行结果

在这里插入图片描述

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值