---
title: Linking, loading and startup code
heading: How separate source files become one program in memory
eyebrow: C8 · Lesson 30 · Linking, loading and startup code
xp: 40
---

::: hook
Real firmware is dozens of source files and a few libraries, compiled one at a time. When `main.c` calls `uart_send` from another file, the compiler has no idea where that function will end up, and when it writes `int count = 5;` it can't put the 5 in RAM, because RAM forgets everything when the power goes off. The linker and a few dozen instructions of startup code solve both problems. Knowing what they do explains where every byte of a program lives, why a microcontroller's flash and RAM fill up the way they do, and what runs before `main`.
:::

::: play
- This is the startup code a microcontroller runs at reset, before `main`. The initial values of `.data` (7, 42, 1000) sit in flash at 0x1000; the RAM at 0x1100 holds leftover junk at power-up.
- Step it. The first loop copies the three initial values into RAM; the second clears the four words of `.bss` that follow. Watch the memory window change.
- Then it sets sp and calls `main`, which finds its variables ready: a0 = 42 and a1 = 0.
:::
:::

```sim cpu
.data
flash: .word 7, 42, 1000          # .data's initial values, as stored in flash
.space 244                         # (the gap up to 0x1100)
ram: .word 5, 5, 5, 9, 9, 9, 9     # RAM at power-up: junk
.text
    la t0, flash         # where .data's initial values are stored
    li t1, 0x1100        # where .data lives while the program runs
    li t2, 3             # words of .data
copy:
    beqz t2, clear_bss
    lw t3, 0(t0)
    sw t3, 0(t1)
    addi t0, t0, 4
    addi t1, t1, 4
    addi t2, t2, -1
    j copy
clear_bss:
    li t2, 4             # words of .bss, just after .data
clear:
    beqz t2, start
    sw zero, 0(t1)
    addi t1, t1, 4
    addi t2, t2, -1
    j clear
start:
    li sp, 0x10000
    call main
    ebreak
main:
    li t0, 0x1100
    lw a0, 4(t0)         # the second variable of .data: 42
    lw a1, 12(t0)        # the first variable of .bss: 0
    ret
show: a0, a1, t2, t3
hex: t0, t1
memory: 0x1100..0x111C
speed: 8
```

::: predict
## A program has 20 kB of code, 2 kB of constant tables, 1 kB of initialized variables and 6 kB of variables that start at zero. How much flash does it need?

- [ ] 22 kB
- [x] 23 kB
- [ ] 29 kB
- [ ] 7 kB

::: reveal
23 kB: the code, the constants, and the initial values of the 1 kB of variables, which startup code copies into RAM. The 6 kB of zeroed variables take no flash at all, only a size and an address; startup code clears them.
:::
:::

::: nameit
## From source to running program

1. The **compiler** turns each C file into assembly.
2. The **assembler** turns each into an **object file**: machine code and data in **sections**, a **symbol table** (the names it defines and the names it uses but doesn't define), and **relocations**, notes of every place that needs an address it doesn't know yet.
3. The **linker** combines the object files and libraries, places each section at an address given by a **linker script** (the chip's memory map), resolves every symbol, and patches every relocation. The result is an executable (an ELF file) or a raw image.
4. A **loader** puts it in memory: an operating system reads it from disk, while a microcontroller has it programmed into flash once.

## Sections

| Section | Holds | Lives in |
|---|---|---|
| `.text` | code | flash |
| `.rodata` | constants, string literals, tables | flash |
| `.data` | initialized variables | RAM, with the initial values stored in flash |
| `.bss` | variables that start at zero | RAM only |
| stack, heap | locals, saved registers, dynamic memory | RAM |

so flash = .text + .rodata + .data, and RAM = .data + .bss + stack + heap.

## Startup code

Before `main`, the reset handler copies `.data`'s initial values from flash to RAM, fills `.bss` with zeros, sets sp, and calls `main`. C guarantees that globals start at their values or at zero; this is the code that keeps that promise.

## Addresses relative to the PC

`auipc rd, imm` puts PC + imm × 4096 in rd. The assembler writes `la rd, symbol` as `auipc` plus `addi`, splitting the distance from the PC into an upper part and a signed lower 12 bits (rounding the upper part as `lui` and `addi` do). The code then works wherever it's loaded, as long as the distance stays the same.
:::

::: example
## A program's map file lists `.text` 18,400 bytes, `.rodata` 2,100, `.data` 600 and `.bss` 3,200, with a 2,048-byte stack. How much flash and RAM does it use?

::: solution
1. **Flash.** `.text`, `.rodata` and the initial values of `.data`:
   $$\begin{aligned} &18{,}400 + 2{,}100 + 600 \\ &= 21{,}100\ \text{bytes} \end{aligned}$$
2. **RAM.** `.data`, `.bss` and the stack:
   $$\begin{aligned} &600 + 3{,}200 + 2{,}048 \\ &= 5{,}848\ \text{bytes} \end{aligned}$$
3. **Fit.** On a chip with 32 kB of flash and 8 kB of RAM there's room for both, but the RAM is 71% full.

**Answer:** 21,100 bytes of flash and 5,848 bytes of RAM.
:::
:::

::: example
## `la a0, table` sits at 0x0040, and `table` is at 0x1830. What do the `auipc` and `addi` hold?

::: solution
1. **The distance.**
   $$\begin{aligned} d &= \text{0x1830} - \text{0x0040} \\ &= \text{0x17F0} \\ &= 6128 \end{aligned}$$
2. **Split it.** Its low 12 bits, 0x7F0 = 2032, fit as a positive signed number, so the upper part is 0x17F0 >> 12 = 1.
3. **The `auipc`.** `auipc a0, 1` gives 0x0040 + 0x1000 = 0x1040.
4. **The `addi`.** `addi a0, a0, 2032` reaches 0x1830.

**Answer:** `auipc a0, 1` and `addi a0, a0, 2032`.
:::
:::

::: example
## Startup code copies 600 bytes of `.data` from flash to RAM (5 instructions a word) and zeroes 3,200 bytes of `.bss` (3 instructions a word). How long does that take at 16 MHz, one instruction a cycle?

::: solution
1. **Copying `.data`.**
   $$150\ \text{words} \times 5 = 750$$
   instructions.
2. **Zeroing `.bss`.**
   $$800\ \text{words} \times 3 = 2{,}400$$
   instructions.
3. **Time.** Together 3,150 cycles:
   $$\frac{3{,}150}{16\ \text{MHz}} \approx 197\ \mu\text{s}$$
4. **What it means.** That's why a C program's globals already hold their initial values when `main` starts: the reset handler put them there, and `.bss` costs no flash because only its size is stored.

**Answer:** 3,150 cycles, about 197 µs.
:::
:::

::: check
kind: parts
given: T = 12 | 30 | 60; R = 1 | 4; D = 0.5 | 2; B = 3 | 10; S = 1 | 2

## A firmware image has {T} kB of `.text`, {R} kB of `.rodata`, {D} kB of `.data` and {B} kB of `.bss`, and reserves {S} kB of stack.

::: part
answer: T + R + D
unit: kB
tolerance: 0.5%

### How much flash does it need?

::: misses
- [T + R] `.data`'s initial values are stored in flash too.
- [T + R + D + B] `.bss` starts at zero, so nothing for it is stored in flash.
- [any] Not yet. .text + .rodata + .data.
:::
:::

::: part
answer: D + B + S
unit: kB
tolerance: 0.5%

### How much RAM does it need?

::: misses
- [B + S] `.data` lives in RAM while the program runs.
- [any] Not yet. .data + .bss + stack.
:::
:::
:::

::: check
given: P = 256 | 4096 | 8192; k = 1 | 2 | 5
answer: P + k*4096
base: 16
width: 4

## What does `auipc t0, {k}` at address {P:hex4} put in t0?

::: right
Right. PC + {k} × 4096.
:::

::: misses
- [k*4096] auipc adds to the PC: that's what makes it position-independent.
- [P + k] The immediate is shifted up 12 bits.
- [any] Not yet. PC + imm × 4096.
:::
:::

::: check
kind: parts
given: P = 64 | 512; A = 6144 | 7000 | 10000 | 14000; let d = A - P; let hi = floor((d + 2048)/4096)

## `la a0, buf` sits at {P:hex4}, and `buf` is at {A:hex4}.

::: part
answer: hi
tolerance: 0

### What immediate does the `auipc` hold?

::: misses
- [any] The distance, rounded to a multiple of 4096 so the remainder fits in a signed 12-bit field.
:::
:::

::: part
answer: d - 4096*hi
tolerance: 0

### What immediate does the `addi` hold?

::: misses
- [any] The distance minus 4096 × the upper part.
:::
:::
:::

::: check
given: D = 512 | 2048 | 8192; k = 5 | 6; f = 16 | 48
answer: D/4*k/f
unit: µs
tolerance: 0.5%

## Startup code copies {D} bytes of `.data` a word at a time, taking {k} cycles per word on a {f} MHz clock. How long does the copy take?

::: right
Right. {D}/4 words × {k} cycles / {f} MHz.
:::

::: misses
- [D*k/f] It copies a word, 4 bytes, per pass.
- [any] Not yet. Words × cycles per word / clock rate.
:::
:::

::: check
kind: order

## Put the steps that turn two C files into a running microcontroller program in order.

1. Compile each C file to assembly
2. Assemble each into an object file with relocations
3. Link the object files, placing sections by the linker script
4. Program the image into flash
5. At reset, copy .data to RAM and clear .bss
6. Call main

::: right
Right. The first three happen on the computer; the last two every time the chip starts.
:::
:::

::: check
kind: choice

## A global `int count = 5;` is declared in a C file for a microcontroller. Where is count while the program runs, and where does its 5 come from?

- [ ] In flash, written there by the programmer
- [x] In RAM, copied from flash by the startup code
- [ ] In RAM, set to 5 by the linker
- [ ] In a register, loaded at reset

::: misses
- [1] A variable has to be writable, and flash can't be written one word at a time like RAM.
- [3] The linker only builds the image; it isn't running when the chip starts.
- [4] Globals live in memory; registers are reused all the time.
:::
:::

::: check
kind: parts
given: D = 400 | 1200; Z = 2000 | 8000; f = 8 | 16 | 48

## Startup copies {D} bytes of `.data` (5 instructions a word) and zeroes {Z} bytes of `.bss` (3 a word) at {f} MHz.

::: part
answer: 5*D/4 + 3*Z/4
tolerance: 0

### How many instructions does that take?

::: misses
- [5*D + 3*Z] Count words, not bytes.
- [any] Words × instructions per word, for each section.
:::
:::

::: part
answer: (5*D/4 + 3*Z/4)/f
unit: µs
tolerance: 0.5%

### How long, at one instruction a cycle?

::: misses
- [any] Instructions ÷ clock.
:::
:::
:::

::: check
kind: parts
given: T = 9000 | 24000; R = 800 | 3000; D = 256 | 900; Z = 1500 | 6000; K = 1024 | 4096

## A map file lists `.text` {T}, `.rodata` {R}, `.data` {D} and `.bss` {Z} bytes, with a {K}-byte stack.

::: part
answer: T + R + D
tolerance: 0

### How much flash does it use?

::: misses
- [T + R] The initial values of `.data` are stored in flash.
- [any] Code, constants and the initial data.
:::
:::

::: part
answer: D + Z + K
tolerance: 0

### And how much RAM?

::: misses
- [Z + K] `.data` lives in RAM while the program runs.
- [any] Data, zeroed data and the stack.
:::
:::
:::

::: explain
## Why can't the assembler fill in the address of a function defined in another source file, and what fills it in?

::: model
Each file is assembled on its own, so the assembler sees only that file: it knows where things are relative to the start of its own sections, but not where the linker will put those sections in memory, and it has never seen the other file at all. So it leaves a placeholder in the instruction and records a relocation saying which symbol belongs there and how to encode it. The linker, which sees every object file and the memory map, decides where every section goes, looks up each symbol's final address, and patches each relocation with the right bits.
:::
:::

::: practice

::: check
given: T = 8 | 40; R = 1 | 3; D = 1 | 4
answer: T + R + D
unit: kB
tolerance: 0.5%

## {T} kB of code, {R} kB of constants and {D} kB of initialized data: how much flash?

::: misses
- [any] The initial values of .data are in flash too.
:::
:::

::: check
given: D = 1 | 2; B = 4 | 12; S = 1 | 4
answer: D + B + S
unit: kB
tolerance: 0.5%

## {D} kB of .data, {B} kB of .bss and {S} kB of stack: how much RAM?

::: misses
- [any] All three live in RAM.
:::
:::

::: check
given: P = 512 | 2048; k = 2 | 3
answer: P + k*4096
base: 16
width: 4

## What does `auipc t1, {k}` at {P:hex4} produce?

::: misses
- [any] PC + imm × 4096.
:::
:::
:::
