Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

7556421251850319424-3765949904798924751-3765949904798924751-3765949904798924751-3765949904798924751

expected:

1491625

What have I missed?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading