From source code to firmware
What happens between typing C and a microcontroller running it: preprocessing, compiling, linking, memory sections, flashing and bootloaders.
Lesson 1 of 6 · 30 min · Self-paced · Free
Text in, behaviour out
You write a few lines of C on a laptop. Minutes later, a robot's motor controller is running them, with no keyboard, screen or operating system. In between, your text passes through a chain of tools that turn it into firmware: the exact bytes stored in the chip's flash memory. When something goes wrong, the error message tells you which stage failed, and knowing the stages lets you fix problems in minutes rather than hours.
Cross-compiling
Your laptop's processor and your microcontroller's processor usually understand completely different machine instructions. So embedded developers use a cross-compiler: a compiler that runs on one kind of computer and produces code for another. The ideas below are the same whether you compile for your laptop or for a chip; only the final steps differ.
Stage 1: the preprocessor
Before compiling, the preprocessor handles every line beginning with #:
#include "scale.h"pastes the contents of that file in place.#define VREF_MV 3300replaces every laterVREF_MVwith3300.#ifdefand friends include or skip blocks of code.
The result is one long C file with no # lines left. You can see it with cc -E main.c.
Stage 2: the compiler
The compiler translates each C file on its own into an object file (.o) containing machine code. It checks syntax and types, and this is where you get errors such as a missing semicolon or an undeclared variable. With -Wall it also issues warnings about code that is legal but suspicious. Treat warnings as bugs that have not happened yet.
An object file is not yet a program. If main.c calls a function defined in scale.c, the compiler just leaves a note: "something called counts_to_mv goes here."
Stage 3: the linker
The linker combines all the object files and libraries, fills in those notes with real addresses, and decides where everything lives in memory. For a microcontroller, a linker script describes the chip's memory: where flash starts, how big it is, where RAM is. If a function is called but never defined, the linker fails with an "undefined reference" or "undefined symbol" error.
Try it on your own computer
You can practise all of this with any C compiler. Create three files.
/* scale.h */
#ifndef SCALE_H
#define SCALE_H
/* Convert a 10-bit reading (0 to 1023) to millivolts for a 3300 mV reference. */
long counts_to_mv(long counts);
#endif/* scale.c */
#include "scale.h"
long counts_to_mv(long counts) {
return counts * 3300 / 1024;
}/* main.c */
#include <stdio.h>
#include "scale.h"
int main(void) {
long reading = 620;
printf("%ld counts = %ld mV\n", reading, counts_to_mv(reading));
return 0;
}The #ifndef lines in the header are an include guard: they stop the header being pasted twice if several files include it. Now build each stage separately:
cc -std=c99 -Wall -c main.c # compile: produces main.o
cc -std=c99 -Wall -c scale.c # compile: produces scale.o
cc main.o scale.o -o reader # link: produces the program
./readerOutput:
620 counts = 1998 mVNow try linking without scale.o: cc main.o -o broken. Both files compiled happily, but the linker stops with an error naming counts_to_mv as undefined. The exact wording differs between compilers, but the meaning is the same: declared, used, never defined. Recognising that this is a link error, not a compile error, immediately tells you to look for a missing file or library rather than a typo.
Where everything goes: memory sections
The linker sorts your program into sections:
- text: machine code and constant data. Goes in flash.
- data: global variables with starting values, such as
int mode = 3;. Their starting values are stored in flash, and start-up code copies them into RAM. - bss: global variables that start at zero. They take RAM, and start-up code fills them with zeros, but they need no space in flash.
The stack, which holds local variables and function return addresses, uses whatever RAM is left. Most embedded toolchains include a size tool that reports these sections. Suppose (made-up numbers for illustration) it reports text = 6,240 bytes, data = 120 bytes and bss = 880 bytes, for a chip with 32 KB of flash and 2 KB of RAM:
flash used = text + data = 6 240 + 120 = 6 360 bytes (about 19 % of 32 768)
RAM used = data + bss = 120 + 880 = 1 000 bytes (about 49 % of 2 048)That leaves about 1 KB for the stack. Check this report every time you add a large array: running out of RAM does not give a polite error at run time; the stack quietly overwrites your variables.
Stage 4: flashing
The linked output, often an ELF file containing code plus debugging information, is converted into a raw binary or a hex file listing bytes and addresses. Then it must get into the chip's flash. There are two common ways:
- A programmer or debug probe: a small device that connects to dedicated pins on the chip and writes flash directly. It can also pause the CPU, step through code and read variables, which makes it the most powerful debugging tool you have.
- A bootloader: a small program already stored in a protected part of flash. After reset, it runs first and checks whether new firmware is arriving, for example over USB or a serial port. If so, it writes the new firmware into flash; if not, it jumps to your application. Many hobby boards work this way, so you can upload over a plain USB cable.
A bootloader is convenient and enables updates in the field, but it occupies some flash, adds a short delay at start-up, and must be protected carefully: if an update is interrupted halfway, a well-designed bootloader keeps the old firmware or waits for a retry rather than leaving the device unusable.
Recap
The preprocessor expands #include and #define; the compiler turns each C file into an object file and reports syntax and type errors; the linker joins object files, resolves names and places sections in memory according to the chip's layout. Code and constants live in flash; initialised and zeroed globals take RAM, with the stack in what remains. The result is flashed through a debug probe or a bootloader. Every error message belongs to one stage, and knowing which stage narrows the search.
Project
Break the build on purpose
Create the three files from this lesson and build them stage by stage. Then cause, and record, one error from each stage:
- Preprocessor: misspell the header name in
#include "scale.h". - Compiler: delete a semicolon in
scale.c. - Linker: link without
scale.o. - Warning: declare an unused variable inside
mainand compile with-Wall.
For each, copy the key line of the message and write one sentence saying which stage produced it and how you could tell. Finally, run cc -E main.c and describe what happened to the #include lines.
Deliverables
- Four recorded messages, each labelled with the stage that produced it
- One sentence per message explaining how you identified the stage
- A short description of the preprocessor output
Knowledge check
Check your understanding
Go further
- Linker (computing) (Wikipedia) ↗
How linkers combine object files and resolve symbols.
- Bootloader (Wikipedia) ↗
What bootloaders do in computers and embedded devices.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.