aboutsummaryrefslogtreecommitdiff
path: root/content/notes
diff options
context:
space:
mode:
authorMitja Felicijan <mitja.felicijan@gmail.com>2024-06-17 16:27:35 +0200
committerMitja Felicijan <mitja.felicijan@gmail.com>2024-06-17 16:27:35 +0200
commit554ac2d2b0b72b890ede5bf50c0ae6ed5bcceca1 (patch)
treec049f3445aae9359b2e6f39dab8fa9b5511ba565 /content/notes
parent7bab7599e21717b1341de131f9c9a15a42f29857 (diff)
downloadmitjafelicijan.com-554ac2d2b0b72b890ede5bf50c0ae6ed5bcceca1.tar.gz
Note: Calling assembly functions from C
Diffstat (limited to 'content/notes')
-rw-r--r--content/notes/2024-06-17-calling-assembly-functions-from-c.md48
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---
2title: "Calling assembly functions from C"
3url: calling-assembly-functions-from-c.html
4date: 2024-06-17T16:12:13+02:00
5type: note
6draft: false
7---
8
9This is using the portable GNU assembler and TinyCC compiler but GCC or Clang
10can be used as well.
11
12First 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
22sum:
23 add rdi, rsi
24 mov rax, rdi
25 ret
26```
27
28Lets compile this with GNU assembler `as sum.s -o sum.o`.
29
30Now 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.
37int sum(int a, int b);
38
39int 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
47Now lets compile and link into final program with `tcc main.c sum.o -o main`.
48