;;; Read integers and take their sum. I/O is performed by calling the ;;; standard C library global _start extern printf extern scanf extern exit ;;; Text section means code. Variables go in the .data section. Sections ;;; are in different places, and the assembler adds the declarations to the ;;; end of the current section. section .text _start: ;; Print the initial instructions. mov rdi, inmsg call printf ;; We'll keep the sum in r12, which under the register protocol ;; functions should preserve. mov r12,0 nextno: ;; Read the value. mov rdi, prompt call req ;; See if the entered value is -1, and if so print and end. ;; The %d of printf and scanf uses 32-bit values. Using ;; eax here refers to the low 32 bits of rax excludes the ;; extra bits from the comparison. cmp eax,-1 je done ;; Add to the sum add r12,rax ;; Next number. jmp nextno done: ;; Print the result. mov rdi,ansmsg mov rsi,r12 call printf ;; We're done. mov rdi, 0 call exit section .data inmsg: db 'Enter numbers to sum, end with -1.',10,0 prompt: db '>',0 ansmsg: db 'The result is %d',10,0 ;;; Request and return an integer. Argument is a prompt string. Performs ;;; a 32-bit read using scanf %d. section .text req: sub rsp,8 ; Put room on the stack for the result ;; Make the prompt. Move our argument to second argument, then ;; insert the "%s: " string for printf and call it. mov rsi,rdi mov rdi,prfmt call printf ;; Read the value using scanf. Scanf takes a pointer (sent as ;; the second parameter is rsi, which is a copy of the stack ;; pointer), and puts the value there. Then we pop it into rax ;; which is where return values go. mov rdi,rdfmt mov rsi,rsp ; Address of the temp variable on the stack. call scanf pop rax ; Pop the read value into the return reg. ;; Done. ret section .data prfmt: db '%s ',0 ; Printf format for printing the promt. rdfmt: db '%d',0 ; Scanf format for reading an integer value.