0Pricing
Assembly Language & x86 Low-Level Systems Programming · Aula

Chamando C a partir de Assembly

Compreenda como invocar funções C no seu código Assembly seguindo as convenções padrão de chamada.

Chamando C a partir de Assembly é uma aula grátis de Assembly Language & x86 Low-Level Systems Programming no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Assembly Language & x86 Low-Level Systems Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Assembly Language & x86 Low-Level Systems Programming inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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:

  1. push dword arg3_value
  2. push dword arg2_value
  3. push dword arg1_value
  4. call 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.
  • extern Directive: 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!

Perguntas Frequentes

A aula “Chamando C a partir de Assembly” é grátis?

Sim — o texto completo de “Chamando C a partir de Assembly” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Assembly Language & x86 Low-Level Systems Programming, atualize para CoddyKit PRO. O curso de Assembly Language & x86 Low-Level Systems Programming inclui 4 aulas no total.

O que vou aprender em “Chamando C a partir de Assembly”?

Compreenda como invocar funções C no seu código Assembly seguindo as convenções padrão de chamada. Você pratica Assembly Language & x86 Low-Level Systems Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Assembly Language & x86 Low-Level Systems Programming?

Nenhuma experiência prévia é necessária. Assembly Language & x86 Low-Level Systems Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Chamando C a partir de Assembly”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Assembly Language & x86 Low-Level Systems Programming?

Sim. Cada aula de Assembly Language & x86 Low-Level Systems Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Chamando Assembly a partir de C
  2. Chamando C a partir de Assembly
  3. Técnicas de Programação em Múltiplas Linguagens
  4. Convenções de chamada: cdecl, stdcall e System V
← Voltar para Assembly Language & x86 Low-Level Systems Programming