Skip to content

Instantly share code, notes, and snippets.

@hibariya
Last active November 11, 2022 10:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hibariya/d7fab1b5b0ca9ca2c6000bbdc396849e to your computer and use it in GitHub Desktop.
Save hibariya/d7fab1b5b0ca9ca2c6000bbdc396849e to your computer and use it in GitHub Desktop.
Calling c function from x86 assembly code (cdecl)
#include <stdio.h>
int add_print(int a, int b) {
int c = a + b;
printf("%d + %d = %d\n", a, b, c);
return c;
}
global main
extern add_print
section .text
main:
; int eax = add_print(1, 2); // => 3
push dword 2
push dword 1
call add_print
add esp, 8
; add_print(2, eax); // => 5
push dword eax
push dword 1
call add_print
add esp, 8
; return 0;
mov eax, 0
ret
OBJECTS = func.o main.o
CC = gcc
CFLAGS = -std=c11 -m32 -Wall -Wextra -Werror -c
AS = nasm
ASFLAGS = -f elf
all: $(OBJECTS)
gcc -m32 $(OBJECTS) -o main
run: all
./main
%.o: %.c
$(CC) $(CFLAGS) $< -o $@
%.o: %.s
$(AS) $(ASFLAGS) $< -o $@
clean:
rm -rf $(OBJECTS) main
@KilroyWasHere-cs-j
Copy link

It should be noted that if you're using an x64 change "-m32" in the Makefile to "-m64". It didn't work for me without doing that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment