首页 > 解决方案 > 无法理解 nasm 错误。如何修复代码。

问题描述

我尝试从 asm 代码调用 printf 函数。

你好.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

生成文件:

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

请解释错误以及如何修复代码。

谢谢。

标签: assemblyx86nasmx86-64

解决方案


两条错误消息都提供了很好的线索。它们发生在第 16 行和第 19 行。

在第 16 行中,您有:

sub 8, rsp

这里的问题是你不能从字面常量中减去(任何东西)。我认为实际意图是

sub rsp, 8

对于第 19 行也是如此。而不是

add 8, rsp

你想要的是

add rsp, 8

sub考虑到对于和等指令add,第一个操作数获取操作的结果。而文字常量不能做到这一点!


推荐阅读