Writing Functions in Assembler Code
Content |
We give a minimalistic example on how a function written in assembly code can be called from a C program:
-
The C program calling an external function:
#include <stdio.h> #include <stddef.h> // for size_t #include <stdint.h> // for uint64_t // forward declaration uint64_t factorial(uint64_t n); int main() { size_t n; printf("n = "); scanf("%zu", &n); n = factorial(n); printf("n! = %zu\n", n); }
-
The function written in assembly code
# uint64_t # factorial(uint64_t n); # Note: n is passed in register %rdi # the retrun value is passed in register %rax .globl factorial factorial: movq $1, %rax jmp .check .loop: imulq %rdi, %rax decq %rdi .check: cmpq $1, %rdi jg .loop retq
Exercise
Compile, link an run the code.