diff options
| -rw-r--r-- | content/notes/2024-06-17-calling-assembly-functions-from-c.md | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/content/notes/2024-06-17-calling-assembly-functions-from-c.md b/content/notes/2024-06-17-calling-assembly-functions-from-c.md new file mode 100644 index 0000000..41e50e8 --- /dev/null +++ b/content/notes/2024-06-17-calling-assembly-functions-from-c.md | |||
| @@ -0,0 +1,48 @@ | |||
| 1 | --- | ||
| 2 | title: "Calling assembly functions from C" | ||
| 3 | url: calling-assembly-functions-from-c.html | ||
| 4 | date: 2024-06-17T16:12:13+02:00 | ||
| 5 | type: note | ||
| 6 | draft: false | ||
| 7 | --- | ||
| 8 | |||
| 9 | This is using the portable GNU assembler and TinyCC compiler but GCC or Clang | ||
| 10 | can be used as well. | ||
| 11 | |||
| 12 | First lets define a simple function in assembly. | ||
| 13 | |||
| 14 | ```asm | ||
| 15 | # sum.s | ||
| 16 | .intel_syntax noprefix | ||
| 17 | |||
| 18 | .global sum | ||
| 19 | |||
| 20 | .text | ||
| 21 | |||
| 22 | sum: | ||
| 23 | add rdi, rsi | ||
| 24 | mov rax, rdi | ||
| 25 | ret | ||
| 26 | ``` | ||
| 27 | |||
| 28 | Lets compile this with GNU assembler `as sum.s -o sum.o`. | ||
| 29 | |||
| 30 | Now we need a C program that calls this function. | ||
| 31 | |||
| 32 | ```c | ||
| 33 | // main.c | ||
| 34 | #include <stdio.h> | ||
| 35 | |||
| 36 | // We need to define the signature of the function. | ||
| 37 | int sum(int a, int b); | ||
| 38 | |||
| 39 | int main() { | ||
| 40 | for(int i=0; i<10; ++i) { | ||
| 41 | printf("SUM of 5+%d is %d\n", i, sum(5, i)); | ||
| 42 | } | ||
| 43 | return 0; | ||
| 44 | } | ||
| 45 | ``` | ||
| 46 | |||
| 47 | Now lets compile and link into final program with `tcc main.c sum.o -o main`. | ||
| 48 | |||
