diff options
| author | Mitja Felicijan <mitja.felicijan@gmail.com> | 2024-06-17 16:27:35 +0200 |
|---|---|---|
| committer | Mitja Felicijan <mitja.felicijan@gmail.com> | 2024-06-17 16:27:35 +0200 |
| commit | 554ac2d2b0b72b890ede5bf50c0ae6ed5bcceca1 (patch) | |
| tree | c049f3445aae9359b2e6f39dab8fa9b5511ba565 /content/notes | |
| parent | 7bab7599e21717b1341de131f9c9a15a42f29857 (diff) | |
| download | mitjafelicijan.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.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 | |||
