NASM:尝试添加2个变量

时间:2014-09-23 03:44:46

标签: variables add nasm system-calls

global _start

section .data

section .bss     ;declares 3 variables
num1:   resb 4
num2:   resb 4
sum:    resb 4
section .text

_start:
mov     ecx, num1
mov     edx, 02h

call        read
call        write

mov     ecx, num2
mov     edx, 02h

call        read2
call        write2

;mov        ecx, sum
;mov        edx, 02h

mov     ecx, num1
add     ecx, num2
mov     sum, ecx

je      exit

exit:   ;exits the program
mov     eax, 01h        ; exit()
xor     ebx, ebx        ; errno
int     80h

read:   ;reads input from the keyboard and stores it in ecx
mov     eax, 03h        ; read()
mov     ebx, 00h        ; stdin
mov     ecx, num1
int     80h
ret

read2:   ;reads input from the keyboard and stores it in ecx
mov     eax, 03h        ; read()
mov     ebx, 00h        ; stdin
mov     ecx, num2
int     80h
ret

write:   ;outputs the contents of ecx to stdout
mov     eax, 04h        ; write()
mov     ebx, 01h        ; stdout
mov     ecx, num1
int     80h
ret

write2:   ;outputs the contents of ecx to stdout
mov     eax, 04h        ; write()
mov     ebx, 01h        ; stdout
mov     ecx, num2
int     80h
ret

我需要帮助将2个变量加在一起。我一直收到来自invalid combination of opcode and operands行的mov sum, ecx个错误。感觉就像我已经尝试了几十种没有真正运气的组合。一旦我将变量添加到sum变量,我还需要将结果打印到stdout

1 个答案:

答案 0 :(得分:0)

您收到错误是因为您试图将ecx移动到立即操作数,这是不可能的。

mov     ecx, num1 ; num1 is the address of the "num1" label
add     ecx, num2 ; num2 is the address of the "num2" label
mov     sum, ecx  ; sum is the address of the "sum" label

因此,根据标签的地址,您的代码会转换为:

mov     ecx, 0x401800
add     ecx, 0x401804
mov     0x401808, ecx

......你可能不想要。 如果要使用地址中的内容,则必须使用方括号:

mov     ecx, [num1] ; get contents at "num1"
add     ecx, [num2] ; get contents at "num2"
mov     [sum], ecx  ; move ecx to address "sum"