我尝试从asm代码调用printf函数。
hello.asm:
%macro exit 0
mov eax, 1
mov ebx, 0
int 80h
%endmacro
extern printf ; the C function, to be called
SECTION .data
hello: db 'Hello world!', 0
SECTION .text
GLOBAL main
main:
sub 8, rsp
push dword hello
call printf ; Call C function
add 8, rsp
exit
Makefile文件:
all:
nasm -f elf64 hello.asm -o hello.o
ld hello.o -e main -o hello -lc -I/lib/ld-linux.so.2
clean:
rm -f hello.o hello
打电话:
nasm -f elf64 hello.asm -o hello.o
hello.asm:16: error: invalid combination of opcode and operands
hello.asm:19: error: invalid combination of opcode and operands
make: *** [all] Error 1
请解释错误以及如何修复代码。
谢谢。
这两条错误消息都提供了很好的线索。它们发生在第16和19行。
第16行你有:
sub 8, rsp
这里的问题是你不能从文字常量中减去(任何东西)。我认为实际意图是
sub rsp, 8
对于第19行也是如此
add 8, rsp
你想要的是什么
add rsp, 8
考虑到对于诸如sub
和add
之类的指令,第一个操作数获取操作的结果。字面常量不能这样做!
工作方案:
你好ç:
extern exit ; the C function, to be called
extern puts ; the C function, to be called
SECTION .data
hello: db 'Hello world!', 0
SECTION .text
GLOBAL _start
_start:
mov edi, hello
call puts ; Call C function
mov edi, 0
call exit ; Call C function
Makefile文件:
all:
nasm -f elf64 hello.asm -o hello.o
gcc -nostartfiles -no-pie hello.o -o hello
clean:
rm -f hello.o hello