From 554ac2d2b0b72b890ede5bf50c0ae6ed5bcceca1 Mon Sep 17 00:00:00 2001 From: Mitja Felicijan Date: Mon, 17 Jun 2024 16:27:35 +0200 Subject: Note: Calling assembly functions from C --- ...2024-06-17-calling-assembly-functions-from-c.md | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 content/notes/2024-06-17-calling-assembly-functions-from-c.md (limited to 'content/notes') 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 @@ +--- +title: "Calling assembly functions from C" +url: calling-assembly-functions-from-c.html +date: 2024-06-17T16:12:13+02:00 +type: note +draft: false +--- + +This is using the portable GNU assembler and TinyCC compiler but GCC or Clang +can be used as well. + +First lets define a simple function in assembly. + +```asm +# sum.s +.intel_syntax noprefix + +.global sum + +.text + +sum: + add rdi, rsi + mov rax, rdi + ret +``` + +Lets compile this with GNU assembler `as sum.s -o sum.o`. + +Now we need a C program that calls this function. + +```c +// main.c +#include + +// We need to define the signature of the function. +int sum(int a, int b); + +int main() { + for(int i=0; i<10; ++i) { + printf("SUM of 5+%d is %d\n", i, sum(5, i)); + } + return 0; +} +``` + +Now lets compile and link into final program with `tcc main.c sum.o -o main`. + -- cgit v1.2.3