kesarling
kesarling

Reputation: 2228

A simple function to square a number in assembly

My second day into assembly programming, I am trying to create a function to square a number
square.asm:

    global square: ; do not need _start because gcc has one already
    section .text
square:
    mov rax, rsi; remember: first argument is always in rsi. (Order is: rsi, rdi, rdx, tcx, r8, r9)
    mul rsi ; rax = rax * rsi (remember: accumulator is the implicit argument)
    ret ; returns the value in accumulator

main.c:

#include <stdio.h>

long int square(long int);

int main() {
    for (long int i = 1; i < 6; i++) {
        printf("%li", square(i));
    }
    return 0;
}

result:

7556421251850319424-3765949904798924751-3765949904798924751-3765949904798924751-3765949904798924751

expected:

1491625

What have I missed?

Upvotes: 1

Views: 638

Answers (1)

Carl Norum
Carl Norum

Reputation: 224972

Your first parameter is in rdi, not rsi, if you're using the System V ABI.

Use:

mov ras, rdi
mul rdi
ret

To make the output easier to read, you'll also want some whitespace or a newline in your print statement:

printf("%li\n", square(i));

And one nitpick - use either int main(void) or int main(int argc, char **argv) for your main function signature. Anything else is undefined.

Upvotes: 2

Related Questions