TExcelTAD
Home › x86-64 Assembly › Linking with C

Linking with C

Few programs are written entirely in assembly. Far more often, assembly and C (or Rust, Go, C++) are mixed: a hot loop or a special instruction in assembly, everything else in a high-level language. The glue is the calling convention you already know, plus a few linker details. The playgrounds on this site link without the C library, so this lesson shows the C side in normal code blocks and runs the assembly side with a small _start harness.

Calling printf from assembly

To use the C library, your program starts at main (the C runtime provides _start, sets things up and calls main), declares the C functions it uses as extern, and is linked with gcc:

nasm
; hello_printf.asm
default rel                     ; RIP-relative addresses, needed for PIE
extern printf
global main

section .rodata
fmt:    db "%s has %d legs", 10, 0

section .data
animal: db "spider", 0

section .text
main:
    sub rsp, 8                  ; align the stack: entry rsp is 16n + 8
    lea rdi, [fmt]              ; argument 1: the format string
    lea rsi, [animal]           ; argument 2: %s
    mov edx, 8                  ; argument 3: %d
    xor eax, eax                ; varargs: al = number of vector registers used
    call printf wrt ..plt       ; call through the PLT (shared library)
    add rsp, 8
    xor eax, eax                ; return 0 from main
    ret
bash
nasm -f elf64 hello_printf.asm -o hello_printf.o
gcc hello_printf.o -o hello_printf      # gcc adds the C runtime and libc
./hello_printf
spider has 8 legs

Three details trip everybody up:

  1. Alignment. rsp must be a multiple of 16 at the call. At the start of main, the return address has made it 16n + 8, so one sub rsp, 8 (or one push) fixes it. A misaligned printf often crashes inside an SSE instruction.
  2. Variadic functions (printf, scanf) read al to know how many xmm registers hold floating-point arguments. Set eax to 0 if there are none.
  3. PIE. Modern gcc builds position-independent executables, so use default rel / lea reg, [label] and call library functions wrt ..plt. Alternatively link with gcc -no-pie.

Writing an assembly function for C

The other direction: implement a function in assembly and call it from C. Follow the ABI and export the symbol with global:

c
// main.c
#include <stdio.h>
#include <stdint.h>

uint64_t sum_array(const uint64_t *values, uint64_t count);   // in sum.asm

int main(void) {
    uint64_t data[] = {5, 10, 15, 20};
    printf("%lu\n", sum_array(data, 4));
    return 0;
}
bash
nasm -f elf64 sum.asm -o sum.o
gcc main.c sum.o -o demo && ./demo
50

The assembly side, here tested from a small _start that calls it exactly as the C code would — pointer in rdi, count in rsi, result in rax:

nasm · try it yourself
section .data
data:   dq 5, 10, 15, 20

section .text
global _start
global sum_array                ; visible to the linker (and to C)

_start:                         ; test harness standing in for main.c
    mov rdi, data
    mov esi, 4
    call sum_array
    mov rdi, rax
    call print_uint

    mov eax, 60
    xor edi, edi
    syscall

; uint64_t sum_array(const uint64_t *values, uint64_t count)
sum_array:
    xor eax, eax                ; total = 0
    test rsi, rsi
    jz .done                    ; count == 0
.loop:
    add rax, [rdi]
    add rdi, 8
    dec rsi
    jnz .loop
.done:
    ret

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
50

The function only uses scratch registers (rax, rdi, rsi), so it needs no saving. If it used rbx or r12–r15, it would have to push and pop them, or the C code calling it would break in mysterious ways.

Matching C types

C type Size Register part Load with
char, int8_t, bool 1 dil, al movzx/movsx
short, int16_t 2 di, ax movzx/movsx
int, int32_t, float (in xmm) 4 edi, eax mov eax, [..], movsxd for signed widening
long, int64_t, pointers, size_t 8 rdi, rax mov rax, [..]
double 8 xmm0… movsd

A function declared to return int only needs to set eax; the upper half of rax is ignored by the caller. Arguments smaller than 64 bits arrive in the low part of the register, and the rest of the register is not guaranteed to be clean — sign- or zero-extend before using the full register.

Here is a function with mixed types, int64_t scale(int32_t value, int8_t shift), tested with negative inputs:

nasm · try it yourself
section .text
global _start
_start:
    mov edi, -300
    mov esi, 2
    call scale
    mov rdi, rax
    call print_int              ; -300 << 2

    mov rdi, 0xFFFFFFFF_00000005  ; garbage in the upper half: value is 5
    mov esi, 3
    call scale
    mov rdi, rax
    call print_int              ; 5 << 3

    mov eax, 60
    xor edi, edi
    syscall

; int64_t scale(int32_t value, int8_t shift) -> value << shift, as a 64-bit result
scale:
    movsxd rax, edi             ; use only the low 32 bits, sign-extended
    movzx ecx, sil              ; the shift count lives in the low byte
    shl rax, cl
    ret

; ---- print_int: print rdi as a signed decimal number and a newline ----
print_int:
    test rdi, rdi
    jns print_uint          ; not negative: print it as it is
    neg rdi                 ; make it positive
    push rdi                ; keep it (write and syscall clobber registers)
    push '-'                ; the minus sign, as a byte on the stack
    mov eax, 1              ; write(1, rsp, 1)
    mov edi, 1
    mov rsi, rsp
    mov edx, 1
    syscall
    pop rdi                 ; drop the '-'
    pop rdi                 ; the positive value again
    jmp print_uint          ; print_uint's ret returns to our caller

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
-1200
40

Inline assembly in C

For a single instruction, a separate .asm file is overkill. GCC and Clang support inline assembly inside C. It uses AT&T syntax by default, and constraints tell the compiler which registers to use: "+r"(total) means "a register holding total, read and written". This one is a real, runnable C program:

c · try it yourself
#include <stdio.h>
#include <stdint.h>

static uint64_t add_asm(uint64_t a, uint64_t b) {
    __asm__("addq %1, %0"          // AT&T order: source, destination
            : "+r"(a)              // output (and input): a
            : "r"(b));             // input: b
    return a;
}

static unsigned popcount_asm(uint64_t x) {
    uint64_t count;
    __asm__("popcntq %1, %0" : "=r"(count) : "r"(x));
    return (unsigned)count;
}

int main(void) {
    printf("%lu\n", add_asm(40, 2));
    printf("%u\n", popcount_asm(0xFF00FF));
    return 0;
}
42
16

Inline assembly is easy to get subtly wrong (forgetting to declare a clobbered register or memory) and blocks many optimizations. Prefer compiler intrinsics (__builtin_popcountll, _mm_add_epi32) when they exist, and separate .asm files for larger routines.

Test yourself

Why does main start with sub rsp, 8 before calling printf?

  1. To reserve space for the return value
  2. To make rsp a multiple of 16 at the call, as the ABI requires
  3. To skip the return address
  4. printf needs exactly 8 bytes

What must al contain when calling a variadic function like printf?

  1. The number of integer arguments
  2. The number of vector (xmm) registers used for arguments
  3. The format string
  4. Nothing; it is ignored

A C function int f(int x) is implemented in assembly. Where is x?

  1. in rdi, with the upper 32 bits guaranteed zero
  2. in edi; the upper half of rdi may contain anything
  3. on the stack
  4. in eax