Calling C functions from assembly

When writing assembly code, it is still often the case that you would like to call library functions written in C. Just because part of your program makes sense to write in assembly, you don’t have to give up the whole C runtime and its features.

The key thing is to use the calling convention to set up the parameters in the right places, call into the function by its name, and know where to find its return value. You don’t need to include any headers to have access to a function by its name; the linker will fix it for you.

For example, say we have the following function in C.

long sillyadd(long a, long b)
{
    return a + b;
}

Obviously, there should be a header somewhere with a declaration like long sillyadd(long a, long b);, but we won’t actually use it in assembly except for reference so we know what the parameters and return type are.

Based on the System V calling convention, the first parameter, a, is passed in rdi, and the second parameter, b, is passed in rsi. The return value will be in rax after the function returns to the instruction after the call. So an assembly code calling sequence to use this function might look like this.

# set up a call like sillyadd(3, 4)
mov esi, 4
mov edi, 3
call    sillyadd
# now 3 + 4 = 7 is in rax
You have attempted of activities on this page