Stephen Thomas
Stephen Thomas

Reputation: 79

Add two numbers in assembly

I'm just getting started with assembly and I wanted to create a simple program that adds two numbers and prints the result

This is what I have so far:

.globl main
   .type main, @function
main:
   movl $14, %eax
   movl $10, %ebx
   add %eax, %ebx
call printf

From my understanding here is what's happening line by line

Line 1: I'm creating a label main that can be accessed by the linker

Line 2: I'm specifying the type of label main to a function

Line 3: I begin my definition of main

Line 4: I store the numeric value 14 into the general register eax

Line 5: I store the numeric value 10 into the general register ebx

Line 6: I add the values at eax and ebx and store the result in ebx

Line 7: I call the function printf(here's where I get confused)

How do I specify what value at which register gets printed?

Also, how do I complete this program? Currently when run, the program results in a segmentation fault.

Upvotes: 4

Views: 64014

Answers (1)

user6567423
user6567423

Reputation: 373

SECTION .data

    extern printf
    global main

fmt:
    db "%d", 10, 0

SECTION .text

main:
    mov     eax, 14
    mov     ebx, 10
    add     eax, ebx

    push    eax
    push    fmt
    call    printf

    mov     eax, 1
    int     0x80

Unfortunately I don't know which compiler/assembler you are using, and I'm not familiar with at&t syntax so I have given you a working example in Intel style x86 for Nasm.

$ nasm -f elf32 test.s -o test.o
$ gcc test.o -m32 -o test
$ ./test
24

In order to use printf you need to actually push the arguments for it onto the stack, I do this here in reverse order (push the last arguments first):

push    eax
push    fmt

EAX contains the result of add eax, ebx and the label 'fmt' is an array of chars: "%d\n\0" (%d format, newline, null terminator).

After calling printf you need to actually exit your program with the exit system call, otherwise (at least for me) the program will segfault AFTER printf even though it worked and you won't see the result.

So these two lines:

mov    eax, 1
int    0x80

are performing the sys_exit system call by placing the ordinal of exit on x86 (1) into EAX, and then invoking interrupt 0x80, this exits the program cleanly.

Upvotes: 12

Related Questions