r/cprogramming • u/Prestigious-Bet-6534 • Dec 15 '25
Calling C functions from assembly
I want to call a C function from assembler and can't get the parameters to work. I have the following two source files:
.global call_funcall_fun:pushq $0xDEADpushq $0xBABEcall funadd $16, %rspret
--
#include <stdio.h>
void call_fun();
voidfun( long a, long b ) {printf( "Arg: a=0x%lx, b=0x%lx\n", a, b );}
intmain() {call_fun();}
The output is Arg: a=0x1, b=0x7ffe827d0338 .
What am I missing?
5
Upvotes
11
u/carry_irl Dec 15 '25
Why dont you call fun from c code and look at the resulting asm code using objdump?
6
u/mfontani Dec 15 '25
See https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI and read more about the (OS-specific!) ABI.
Parameters to functions are, depending on OS and type of the parameter, passed in a specific register up to a number of them; then on the stack.
Which registers are used varies by OS and OS version.
5
u/chriswaco Dec 15 '25
Are you on AMD-64? I think they moved to using registers for most of the parameters. Maybe try something like this, at least on unix:
3
u/j00cifer Dec 15 '25
DEAD BABES are not fun, that’s your problem
3
u/Brilliant-Orange9117 Dec 15 '25
You have to find and learn your platform's ABI. It specifies (among others) how arguments are passed to functions.
1
u/Key_River7180 Dec 27 '25
Well, you should probably use code blocks next time, and don't try to call C from assembly, every compiler uses its own conventions. The most likely cause is that you aren't using
.extern, and that on some compilers, the caller sets up the stack for the called routine (this convention has been largely deprecated and only used by MSVC by the way). Try using inline assembly from C, or just calling the C function from C.