Calling C from Assembly
Understand how to invoke C functions from within your assembly code, adhering to the standard calling conventions.
Calling C from Assembly is a free Assembly Language & x86 Low-Level Systems Programming lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Assembly Language & x86 Low-Level Systems Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Bridge Assembly & C
Why would you want to combine C and Assembly code? It's a powerful technique in low-level and system programming!
- Assembly: Great for performance-critical tasks, direct hardware access, and understanding system internals.
- C: Offers high-level structure, portability, and access to vast libraries.
By calling C functions from Assembly, you can leverage C's complex logic and libraries while retaining Assembly's low-level control for specific tasks.
The Calling Contract
When one function calls another, they need to agree on a set of rules. This 'contract' is known as a calling convention.
It defines crucial aspects of how functions interact:
- How arguments are passed (e.g., on the stack, in registers).
- The order in which arguments are passed.
- Which function is responsible for cleaning up the stack after the call.
- How return values are transmitted back to the caller.
Without these conventions, your assembly code wouldn't know how to prepare data for a C function, or how to interpret its results.
Common `cdecl` Convention
The cdecl (C declaration) calling convention is very common, especially for 32-bit x86 systems (like Linux).
Let's look at its key characteristics:
- Argument Order: Arguments are pushed onto the stack from right to left.
- Stack Cleanup: The caller (your assembly code) is responsible for cleaning up the stack after the function returns.
- Return Values: Integer return values are typically placed in the EAX register.
Understanding cdecl is fundamental for successful interaction between your assembly and C code.
`cdecl` Argument Passing
With 32-bit cdecl, arguments are pushed onto the stack in reverse order. This means the last argument is pushed first, and the first argument is pushed last.
For a C function like my_func(arg1, arg2, arg3);, the assembly call would involve:
push dword arg3_valuepush dword arg2_valuepush dword arg1_valuecall my_func
This ensures that arg1 is at the 'top' of the arguments on the stack, just below the return address pushed by call.
Caller Cleans Up the Stack
One of the defining features of cdecl is that the caller (your assembly code) is responsible for removing the arguments from the stack after the C function returns.
This is typically done by adjusting the stack pointer (ESP) using the ADD ESP, N instruction, where N is the total size of the arguments pushed (e.g., 4 bytes per argument on 32-bit systems).
This cleanup mechanism allows C functions to accept a variable number of arguments (like printf) because the caller knows exactly how many arguments it pushed.
Handling Return Values
When a C function returns a value using cdecl, it places that value in a specific register for the caller to retrieve.
- For integer types (like
int,char,short), the return value is typically stored in the EAX register (on 32-bit x86). - For larger or floating-point types, other registers or memory locations might be used, but EAX is the most common for simple integer returns.
After the CALL instruction returns, you can simply access the EAX register to get the result from your C function.
Declaring External C Functions
Before your assembly code can call a C function, you need to tell the assembler that the function exists but is defined elsewhere. This is done using the extern directive.
Example: extern printf
This directive informs the assembler that printf is an external symbol. During the linking phase, the linker (e.g., gcc) will resolve this symbol to the actual C function's address, allowing your assembly program to execute it.
Example: Basic C Function Call
Let's call a simple C function that takes no arguments and returns nothing. We'll use 32-bit x86 assembly.
First, compile the C code (c_funcs.c):
#include <stdio.h>
#include <stdlib.h>
void greet_c() {
printf("Hello from C's greet_c()!\n");
}
// Placeholder for next example
int add_c(int a, int b) {
return a + b;
}
Now, try running this assembly code:
extern greet_c
extern exit
section .text
global _start
_start:
call greet_c ; Call the C function
; Exit the program
push dword 0 ; Exit status 0
call exit
Example: C with Args & Return
Now, let's call a C function that takes arguments and returns a value. Remember the cdecl rules for 32-bit x86:
- Arguments pushed right-to-left.
- Caller cleans the stack.
- Return value in EAX.
Add the add_c function to your c_funcs.c file (from the previous scene).
Then, run this assembly code:
extern add_c
extern exit
extern printf
section .data
format_str db "Result from C: %d", 0xA, 0
section .text
global _start
_start:
; Call add_c(10, 20)
; Arguments pushed right-to-left on 32-bit stack
push dword 20 ; Push b
push dword 10 ; Push a
call add_c ; Call the C function
; EAX now holds the return value (30)
; Clean up the stack (2 arguments * 4 bytes each = 8 bytes)
add esp, 8
; Now print the result using C's printf
; For 32-bit cdecl, printf args are pushed right-to-left
push eax ; Push result from add_c (in EAX)
push dword format_str ; Push format string address
call printf
add esp, 8 ; Clean up printf's arguments
; Exit the program
push dword 0 ; Exit status 0
call exit
Check Your Knowledge
Consider a C function int calculate(int x, int y, int z); that you want to call from 32-bit x86 assembly using the cdecl calling convention.
Which sequence of assembly instructions correctly prepares the stack and calls calculate with arguments x=5, y=10, z=15, and correctly cleans up the stack?
Recap: Calling C from Assembly
You've successfully learned how to integrate C functions into your assembly programs!
- Calling Conventions: These are crucial rules for function interaction.
cdecl(32-bit): Arguments are pushed onto the stack from right-to-left.- Caller Cleanup: The assembly code (caller) is responsible for removing arguments from the stack using
ADD ESP, N. - Return Values: Integer results from C functions are typically found in the EAX register.
externDirective: Use this to declare C functions to your assembler.
This skill allows you to combine the performance and low-level control of assembly with the rich features and libraries of C!
Frequently asked questions
Is the “Calling C from Assembly” lesson free?
Yes — the full text of “Calling C from Assembly” is free to read here on the web, and the Assembly Language & x86 Low-Level Systems Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Assembly Language & x86 Low-Level Systems Programming course, upgrade to CoddyKit PRO.
What will I learn in “Calling C from Assembly”?
Understand how to invoke C functions from within your assembly code, adhering to the standard calling conventions. You practise Assembly Language & x86 Low-Level Systems Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Assembly Language & x86 Low-Level Systems Programming?
No prior experience is required. Assembly Language & x86 Low-Level Systems Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Calling C from Assembly” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Assembly Language & x86 Low-Level Systems Programming lesson?
Yes. Every Assembly Language & x86 Low-Level Systems Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.