Last active
November 11, 2022 10:35
-
-
Save hibariya/d7fab1b5b0ca9ca2c6000bbdc396849e to your computer and use it in GitHub Desktop.
Calling c function from x86 assembly code (cdecl)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int add_print(int a, int b) { | |
int c = a + b; | |
printf("%d + %d = %d\n", a, b, c); | |
return c; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
@JazzHoneyPerson make
how to Calling x86 assembly function from c code ?
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
Bash command?(