文章目录
- 写在前面
- x86汇编示例(AT&T风格
- ARM汇编示例
- 运行结果
写在前面
汇编程序中也是可以使用头文件的,因为头文件实际上就是预处理中的一环,使用预处理器也对汇编程序中的头文件进行预处理
本文使用的汇编例程:
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