How it works
Multi-file C: headers, macros and builds follows C from zero. Six lessons run on the code bench: an Arduino Uno with a red lamp on pin 13, yellow on 12, green on 11 and a button on pin 2. The project moves to an ESP32-C3.
Each lesson opens a working one-file sketch. You run it, read the serial
monitor, then grow it: you add the second and third files yourself from the
tab bar (fuel.cpp, rover.h, telemetry.cpp, config.h), and the checks
read what the board prints once your files build and link. Several steps ask
you to break the build on purpose first, so you meet each linker error while
you know exactly what caused it.
The lessons
- Many files, one program: preprocess, compile each file on its own,
link. Declarations against definitions, a second file, and the
undefined symbolyou get when two files disagree. - Headers and guards: a rover split into
rover.handrover.cpp, what#includereally pastes, a header read twice and the guard that stops it, and why a function body in a header needsinline. - Macros and their traps: a square that forgets its brackets, a maximum
that reads a sensor twice,
#anddo { } while (0), and when a function does the job better. - Conditional compilation:
#ifand#ifdef, debug lines that cost nothing when off, a version gate, the chip the build is for, and a default a project can override. - extern and static: linkage and lifetime. A global another file reaches
with
extern,staticat file level that keeps a name private, and a static local that remembers. - Build flags: a sketch that reads its own build (
-std,-mmcu,-Os,-fno-exceptions), a config header in place of-Dflags, and the linker throwing away code nothing calls, measured in the build log.
The project: one codebase for two boards
A beacon that builds unchanged for the Uno and the ESP32-C3. The same file
prints int is 2 bytes on one and int is 4 bytes on the other, and the
same sum gives 0 on the Uno and 65536 on the C3. You make the sum portable
with uint16_t, move every board difference into a guarded board.h, then
make it yours: a third board, a feature flag, or a debug header.
What the boards do differently
- The Uno's compiler defines
__AVR__and the C3's defines__riscv. The course tests those, because the compiler sets them on every build; the Arduino build's own names, likeARDUINO_AVR_UNO, come on top. - An int is 2 bytes on the Uno and 4 on the C3, a pointer the same, and a double is only 4 bytes on the Uno.
- On the Uno a string is copied into RAM at startup, so text costs RAM as well as flash. The build log shows both.
- Mokxi's Run, like the Arduino IDE, uses one fixed set of compiler flags
(
-Os, C++17, no exceptions). Projects set their own options in a config header included first, which works the same with any build tool.
After this course
Modern C++ for microcontrollers replaces
many of these macros with constexpr, enum class and templates, and
Pointers and memory in C goes deep on
what the linker puts where in RAM.