Compiler, Linker and the Map File

One new line of C made a gripper’s firmware 40 KB bigger, and it stopped fitting. The linker’s map file shows which line did it, and a few flags and checks stop it happening again.

Learn how C becomes the bytes in flash, how to read the file that lists every one of them, and how to build the same image every time, on any machine.

Pick a build setting, then switch the printf library. Watch the bar of flash bytes pass the line that marks the 128 KiB slot. Then we build, piece by piece, everything underneath: the sections, the linker, the map file, the flags, the budget, CMake and the checks in CI.

You need a little C and the idea that a chip runs the instructions stored in its flash. Lesson Reset to main() shows that idea. We build the rest from zero.

Part of Firmware from Zero to Expertise. Built from primary sources: the GCC, GNU ld, binutils and CMake manuals, and Memfault’s Interrupt articles on the linker map file, GCC flags, a modern C development environment and reproducible builds. The full list is in the Field Guide.

Fit the image in its slot

Illustrative: the gripper image is a made-up project on an STM32L476RG (Cortex-M4, 1 MiB flash) with a 128 KiB application slot. The sizes add up the way real maps do, but they are not measured. The model is in Chapter 4, and Chapter 5 shows how to measure the real thing.

Chapter 0

The Build That Did Not Fit

See how one innocent line breaks a build, and why the program that turns C into flash bytes deserves as much care as the C itself

A small team builds a gripper for a robot arm. The firmware runs on an STM32L476RG, a chip with a Cortex-M4 core and 1 MiB of flash. The team gave the application a 128 KiB slot. The bootloader and an update slot use the rest. The build passes for months.

Then someone wants to log the pressure in kilopascals, with two decimals. They add one line to comms.c: snprintf(buf, sizeof buf, "%.2f kPa", p). The code works on the desk. The build in the cloud turns red.

The message is short: region 'APP' overflowed by 6146 bytes. Nothing in the logic is wrong. The program is simply too big for the room it was given. The line looks tiny, but it asked the C library for a lot of help, and the linker packed all of that help into the image.

This lesson is about that moment. It teaches you to find out what grew, why it grew and how to stop it from growing again. You will also learn to build the same image, bit for bit, on any machine. That is the part of firmware work that happens before a single instruction runs.

The build is a pipeline of small programs

Your C files do not run on the chip. A chain of tools turns them into bytes. The toolchain is that chain: a set of programs that run on your laptop and make code for a different machine. When the machine you build on is not the machine you build for, this is called cross compiling. For a Cortex-M chip the usual toolchain is GCC, with the name arm-none-eabi-gcc. The name says: an Arm target, no operating system, and the Arm embedded binary interface.

The chain has four main steps. The preprocessor expands #include and #define lines into plain C. The compiler turns that C into assembly, the instructions in readable form. The assembler turns assembly into an object file, the machine instructions plus a list of names. The linker joins all the object files into one program, the image, and gives every piece its final address.

Think of a kitchen. The preprocessor reads the recipe cards and pastes in the sub-recipes. The compiler cooks each dish in the order the cards say. The linker plates every dish on one tray and numbers the places. Each step makes a file you can open. Step through the real thing below, using a function that doubles a number.

Walk one function down the pipeline

Each box is a file the build makes. Press Next stage to run one tool and read the file it wrote. Press it again to go on to the end.

The function and the four machine-code bytes are real Thumb-2: lsls r0, r0, #1 encodes as 0x0040 and bx lr as 0x4770, stored low byte first. The address 0x08008184 is made up. A real compiler may choose a different instruction at other settings.

Two things in the last stage matter for the rest of the lesson. First, the object file has no final addresses yet. It only says “I am 4 bytes of code called twice”. The linker decides where it lives. Second, the final binary is only the bytes. The names, the sizes and the reasons are gone. That is why the linker can write a second file, the map file, which keeps the story of what went where. Chapter 3 reads it.

Three kinds of trouble, and where they show up

Build trouble comes in three kinds, and this lesson has a part for each. The first is size: the image does not fit, or it fits so tightly that the next feature breaks it. The second is speed: a flag that saves bytes can cost cycles, and a flag that saves cycles can cost bytes. The third is trust: you build the release on Monday, a customer reports a fault on Friday, and you cannot rebuild the exact image to look at it.

The tools for all three are the same few files and flags. That is good news. You do not need a new idea for each problem. You need to read the build output the way a mechanic reads an engine.

One rule keeps this honest. Every size and cycle count in the gripper project here is illustrative. We made them up so that they add up like real ones. The numbers that come from real sources, such as Memfault’s map-file example, carry their source in the fine print. On a real board you repeat the measurement. Each chapter says how.

The previous lesson, Reset to main(), showed the linker script as a floor plan. This one goes one level up and down: up to the build system that calls the tools, and down to the numbers in the map file.

The road

  1. What an object file holds: the four sections, and what size tells you.
  2. What the linker does: join, place, and say “it does not fit” in bytes.
  3. Reading the map file: find the 40 KB that appeared overnight.
  4. What the flags buy: -O levels, section garbage collection, LTO and what they cost in cycles.
  5. Hunting the big symbol: nm, the cross-reference, and the right fix.
  6. Budgets: flash and RAM plans, and why an update slot halves your room.
  7. CMake and the toolchain file: one place that holds every flag.
  8. Reproducible builds: the same bytes on every machine.
  9. CI and the size gate: a robot that says no before a human has to.
  10. The Field Guide: numbers, a checklist, core code, sources.
The build prints region 'APP' overflowed by 6146 bytes after a one-line change. Which tool output tells you where the extra bytes came from?

Chapter 1

What an Object File Holds

Sort every line of C into one of four sections, and read the three numbers that size prints

Imagine you move house. You pack boxes for four places. Furniture goes to the living room and stays there. Books on a shelf stay on the shelf and nobody changes them. A box marked “set this up on arrival” has to be opened and unpacked. And some rooms are empty on purpose: you only need to know how big they are.

A program has exactly these four kinds of thing, and the compiler sorts them into four sections. A section is a named block of bytes in an object file. The linker moves whole sections around, so the sorting decides where every byte ends up.

The four sections

.text holds the instructions. It sits in flash, because flash keeps its contents when the power goes off. .rodata holds read-only data: constants, lookup tables and string literals. It also sits in flash. Nothing changes it while the program runs.

.data holds variables that start with a value other than zero. Here is the catch. The variable must live in RAM, because the program changes it. But RAM is empty at power-on, so the starting value must be stored somewhere permanent. It is stored in flash. At reset, the start-up code copies the values from flash into RAM. An initialised variable therefore costs bytes twice: once in flash for the starting value and once in RAM for the variable.

.bss holds variables that start at zero, or that have no starting value. The C rules say they start at zero. The image does not store a long run of zeros. It stores only the size, and the start-up code writes zeros into RAM. A big buffer in .bss costs RAM and almost nothing in flash. Lesson Reset to main() shows the copy and the zeroing loop run step by step.

Sort the declarations

Try it on seven real-looking lines. For each one, decide which section the compiler puts it in. The tally of flash and RAM updates as you go.

Sort the lines into sections

Read the line, then choose a section. Flash holds .text, .rodata and the stored starting values of .data. RAM holds .data and .bss.

Choose a section.

Sizes are exact for the declarations shown: 256 floats of 4 bytes is 1,024 bytes, and the string “grip lost\n” is 10 characters plus the closing zero byte. The instruction count of pid_step (180 bytes) is made up.

The three numbers from size

The tool arm-none-eabi-size prints three numbers for an image. Memfault’s map-file article shows one. Read it with the four sections in mind:

   text    data     bss     dec     hex filename
   1704     108      28    1840     730 _build/nrf52840_xxaa.out

text is code plus read-only data. The default (Berkeley) format of size counts read-only data in the text column, as the binutils manual states. data is the initialised variables. bss is the zero-start variables. dec is the sum of the three, 1,704 + 108 + 28 = 1,840, and hex is the same sum in base 16. Source: Memfault Interrupt, “Get the most out of the linker map file”, with a Nordic nRF52840 build.

Now the key step, a worked example. How much flash does that image take? Flash holds text and the stored copy of data: 1,704 + 108 = 1,812 bytes. How much RAM? RAM holds data and bss: 108 + 28 = 136 bytes, plus the stack and any heap, which size cannot see. The dec column is a total of both, so it matches neither memory. Many people read dec as “my flash use” and are wrong by the size of bss.

ColumnWhat it countsLives in flashLives in RAM
textcode and read-only datayesno
datavariables with a starting valueyes, the starting valuesyes, the variables
bssvariables that start at zeronoyes

The mistake that costs RAM twice

A common slip shows up as a symptom first. The firmware is small. The flash is half empty. Yet the program crashes at start-up, or the linker says RAM is full. The reason is often a table written without const.

A lookup table of 256 floats written as float gain[256] = {...} is a variable. The compiler puts it in .data: 1,024 bytes of flash for the starting values and 1,024 bytes of RAM to hold them. Write const float gain[256] and it moves to .rodata. It costs the 1,024 bytes of flash only. The measurement that catches this is the data column of size. If it is large, look for tables that never change. The fix is one word.

The same rule applies to strings. const char *msg = "grip lost" makes a pointer variable that points into .rodata, so the string costs flash only, while char msg[] = "grip lost" copies the string into RAM. The first is almost always what you want.

On real hardware. On an STM32 Nucleo (for example the NUCLEO-L476RG), build any example and run arm-none-eabi-size build/app.elf. Then add const to one big table and run it again. Write down how the data column changes and check that it fell by the table’s size.

An image shows text = 40,000, data = 3,000, bss = 20,000. Roughly how many bytes of flash does it need?

Chapter 2

What the Linker Does

Follow the three jobs of the linker, and see how it turns “too big” into an exact number of bytes

Two people write two files. Ana writes main.c, which calls pid_step(). Ben writes pid.c, which defines it. Each file compiles on its own, at a different time, without seeing the other. When the compiler reaches the call in main.c, it does not know where pid_step will live. So it writes the call with a blank for the address, and leaves a note in the object file: “fill this blank with the address of pid_step”.

The linker is the program that fills those blanks. It has three jobs, always in this order.

Job one: resolve names

Every object file has two lists of symbols, which are names. One list holds the names it defines. The other holds the names it needs but does not define. The linker matches each need to a definition. If a need has no match, the linker stops and names the missing symbol. If two files define the same name, you get multiple definition.

Where do definitions come from? From your object files, and from libraries. A static library, such as libc.a, is an archive: a bag of many object files. The linker does not take the whole bag. It takes only the members that define a name something still needs. Then it checks what those members need, and takes more members for that. The chain stops when no need is left.

This chain is the heart of the 40 KB mystery. Your line calls snprintf. That needs _svfprintf_r from one member. That member needs a number-conversion routine from another, which needs big-number maths from a third, which needs malloc from a fourth. You asked for one function. The chain brought in a dozen files. The map file records every link of the chain in its first section, which is named Archive member included to satisfy reference by file (symbol). Chapter 3 reads it.

Job two: place the sections

Next, the linker gives every section an address. It does not choose them by itself. A text file, the linker script, tells it. The script has two parts. A MEMORY block lists the real memories: a name, a start address, a length. A SECTIONS block says which sections go into which memory, and in what order. Here is a trimmed script for the gripper:

/* gripper.ld: the application slot starts after a 32 KiB bootloader */
MEMORY
{
  APP  (rx)  : ORIGIN = 0x08008000, LENGTH = 128K
  RAM  (xrw) : ORIGIN = 0x20000000, LENGTH = 96K
}
SECTIONS
{
  .isr_vector : { KEEP(*(.isr_vector)) } > APP
  .text       : { *(.text*) *(.rodata*) }     > APP
  .data       : { _sdata = .; *(.data*); _edata = .; } > RAM AT> APP
  .bss        : { _sbss = .; *(.bss*) *(COMMON); _ebss = .; } > RAM
}

Read the .data line slowly. > RAM says the variables run in RAM. AT> APP says their starting values are stored in the application slot. The GNU ld manual names these two addresses. The virtual memory address (VMA) is where the section is when the program runs. The load memory address (LMA) is where it is stored. The manual says: “The load address is specified by the AT or AT> keywords.” For .text the two are equal. For .data they differ, and the start-up code copies from one to the other. The symbols _sdata and _edata are how that code finds the edges.

Lesson Reset to main() walks through ST’s own script for the STM32L476RG line by line. Here the aim is smaller: to see the budget arithmetic that the script enables.

Job three: patch the blanks

Now every section has an address, so the linker can go back to each note. It computes the real address of pid_step and writes it into the blank in the call. This step is relocation. After it, the instructions are final. It also explains why you cannot move a linked image to another address and expect it to run: the addresses are baked into the code.

Where the error comes from

While placing sections, the linker adds up sizes. If the sections for a memory add up to more than its LENGTH, it stops, and says by how much. This is where the message in Chapter 0 comes from. Memfault shows a clean example. They link a small nRF52840 program against three versions of atoi. With a flash limit of 0x800 bytes (2,048), the version from the standard library has a text size of 2,256 bytes. The linker reports region 'FLASH' overflowed by 208 bytes. The arithmetic: 2,256 − 2,048 = 208. A custom atoi brings text down to 1,740 bytes, and it fits.

That is the whole value of a hard limit. Without a LENGTH, the linker happily writes an image that runs off the end of the flash, and the failure appears much later and much further from its cause. With one, the build stops on the day you cross the line.

Try the arithmetic yourself. Set the three sizes, pick a region, and see what the linker would say.

Place the sections, or overflow

The top bar is the flash region. The bottom bar is RAM. Flash holds text plus the stored copy of data. RAM holds data plus bss. Drag a size past the end of its bar.

94,858
1,400
47,704

The Memfault presets use their published text sizes (2,256 and 1,740 bytes) against their 0x800-byte flash region; the arithmetic of 208 bytes matches their message, and their data column is not part of that sum. The gripper preset is the illustrative project: 128 KiB application slot, 96 KiB RAM.

On real hardware. On an STM32 Nucleo, add -Wl,--print-memory-usage to the link flags. The GNU ld manual describes it: it prints the used size, the total size and the used share of each memory region you made. Shrink one region’s LENGTH in the script until the build fails, and compare the reported overflow with the number you expect.

Your code calls snprintf. The image grows by 40 KB. What does the linker's first job explain?

Chapter 3

Reading the Map File

Open the file that lists every byte of the image, and find the 40 KB that appeared overnight

The cloud build is red. You need the answer to one question: which files made the image 40 KB bigger? You could guess. You could read the diff. Or you could open the one file that the linker wrote for exactly this moment: the map file. It is a plain text record of every decision the linker made.

You ask for it with one flag. Memfault’s article gives the line for a Makefile: LDFLAGS += -Wl,-Map=output.map. The -Wl, prefix hands the option to the linker. The GNU ld manual describes the option as: “Print a link map to the file mapfile.” Turn it on in every build, even in a project that fits easily. The file costs nothing, and you will want it on the day it does not fit.

Four parts, always in this order

A map file looks long and scary. It has only four parts that matter. Read them in order and each one answers a plain question.

Part 1: Archive member included. The question: “Why is this library file in my image?” Each entry has two lines. The first is the archive member that was pulled in. The second says who asked for it and for which name. Memfault’s example shows atoi pulled in by main.c.o. This is the chain from Chapter 2, written out.

Part 2: Discarded input sections. The question: “What did the linker throw away?” Unused code that the linker removed is listed here, for example a function of 0x28 bytes that nobody called. Chapter 4 explains how it gets removed.

Part 3: Memory Configuration. The question: “What rooms did the script define?” It is a small table of names, start addresses, lengths and attributes. Memfault’s example reads:

Name             Origin             Length             Attributes
FLASH            0x0000000000001000 0x00000000000ff000 xr
RAM              0x0000000020000008 0x000000000003fff8 xrw

Part 4: Linker script and memory map. The question: “What went where, and how big is it?” This part is the long one, and it is where you look for the 40 KB. For each output section, the file lists the input sections that fed it, with an address, a size and the object file. Here is the shape, using Memfault’s own lines:

.text           0x0000000000001000      0x8c8
 .isr_vector    0x0000000000001000      0x200 _build/nrf52840_xxaa/gcc_startup_nrf52840.S.o

Read one line left to right: the section name (.isr_vector), the address where the linker put it, the size in hex (0x200 is 512 bytes), and the object file it came from. That is all a map line is. The same article says that .text.bsp_board_led_invert is 0x34 bytes (52 bytes) in boards.c.o. Hex is awkward at first. Convert a size by multiplying: 0x71c = 7 × 256 + 1 × 16 + 12 = 1,820.

When a project is built with -ffunction-sections (Chapter 4), each function gets its own line, named .text.<function>. That makes the map far more precise. You can then say “this one function is 1,820 bytes” and not only “this file is big”.

The 40 KB hunt

Here is the method that works. It has three moves, and they are the same for any size problem. First, sort by size, so the big items rise to the top. Second, compare against a good build: the interesting rows are the ones that are new, not the ones that are big. Third, follow the chain back through Part 1 until you reach a line in your code.

The device below holds the gripper’s map before and after the new line, in a simplified form. Choose Before or After to see the sorted input sections. Choose Difference to see only what changed. Tap a bar, or use the buttons, to read its map lines and its “included because” reason.

Find what ate the 40 KB

Each bar is one input section, longest first. Pick a view, then tap bars to open their map lines.

Illustrative: file names follow newlib’s style (lib_a-*.o, as in Memfault’s example), but the sizes and the reference chains are made up so that the difference is exactly 40,960 bytes (40 KiB). A real library’s numbers depend on its version and build options. Addresses are computed from the sizes, starting at 0x08008200. Both maps are the CI’s release build at -O2.

Look at what the Difference view shows. No single huge file appears. Thirteen library members arrived together, the biggest being the full printf engine. Two small nano members left. The new members sum to 47,560 bytes, the two that left sum to 6,600, and the net growth is 40,960 bytes. A review of the diff would never show this. Only the map does, because only the linker knows the whole chain.

Follow the chain back from any new member. Each “included because” line names another library member, and the trail ends at comms.c.o (snprintf). The map has found your line for you.

Two more flags worth knowing

The ld manual lists --cref: “Output a cross reference table.” It adds a table at the end of the map. Each symbol is followed by every file that defines or uses it. That answers “who calls _malloc_r?” in one search. And --print-gc-sections lists the sections that garbage collection removed (Chapter 4).

Reading hex maps by hand is slow once a project is big. Many teams run a small script that sorts the sections by size. Memfault points to the standard nm tool, which can sort symbols by size, and to a map-file summary script from Adafruit. Chapter 5 uses nm.

On real hardware. Add -Wl,-Map=build/app.map to your Nucleo project. Build once. Then add the snprintf line with %f, build again, and compare the two maps with diff or a side-by-side viewer. Note the first new archive member and the line in your code that asked for it.

You compare two maps and find a new 17 KB member, lib_a-vfprintf.o. Where in the map do you find why it is there?

Chapter 4

What the Flags Buy

Flip the optimisation levels, section garbage collection and link-time optimisation, and see what each costs in bytes and in cycles

Your car has a pedal, and a gearbox, and a mode switch for sport or economy. The same engine gives very different results. A compiler is the same. The C code stays fixed, and a handful of flags, which are options typed on the command line, change what machine code comes out. Some flags save bytes. Some save cycles. A few catch bugs. This chapter sorts them by what they buy and what they cost.

The optimisation levels

The GCC manual defines each level in a sentence. -O0: “Reduce compilation time and make debugging produce the expected results. This is the default.” The compiler copies your C almost line for line, keeps every variable in memory, and makes no attempt to be small or fast. -O2: “GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff.” -Os: “Optimize for size.” The manual adds that it enables all -O2 optimisations except those that often increase code size, and the excluded ones include the alignment of functions, jumps, labels and loops.

For a Cortex-M the common choice is -Os, and Memfault’s flags article describes it as the level generally used for embedded systems. The reason is simple. Flash is small, the core is often fast enough, and -Os code is usually only a little slower than -O2. When a hot loop must go faster, you raise the level for that file, not the whole project.

One more fact is easy to miss. The debug flag -g costs no flash. The debug information lives in extra sections of the .elf file that are not loaded onto the chip, so size does not count them. Memfault also recommends -g3, which adds the macro definitions to the debug data so that a debugger can print them. You can ship debug info in every build at no cost in flash.

Throwing away what nobody calls

The second big saver works in two halves. Normally the compiler puts all the functions of one C file into one .text section. The linker moves whole sections, so if you call one function from a big file, the entire file’s code stays. Now add -ffunction-sections -fdata-sections. The compiler gives every function and every variable its own section. Then add -Wl,--gc-sections. The ld manual says: “Enable garbage collection of unused input sections.” The linker starts from the entry point and the vector table, follows every reference, and drops each section that nothing reaches.

A worked example. A vendor HAL file has 20 functions of 400 bytes each, 8,000 bytes in all. Your program calls three. Without the flags, the whole 8,000 bytes stay. With them, 1,200 stay and 6,800 are dropped. For the gripper’s HAL, the model below drops 12,800 bytes. --print-gc-sections lists what was removed, and the removed items also appear in the map’s discarded part (Chapter 3). One caution: the vector table must survive, which is what the KEEP in the linker script is for.

Link-time optimisation

Normally each C file is compiled alone, so the compiler cannot see across files. It cannot inline a small function that lives in another file. Link-time optimisation (LTO) saves the compiler’s internal form in each object, and optimises again when everything is joined. The manual says of -flto: “This option runs the standard link-time optimizer.” The gain is smaller and often faster code. The cost, per Memfault, is that it is slow, hard to debug and hard to control for memory placement, and it can raise stack use. They call it a “last resort”. Treat it as a tool for the last few percent, and measure it.

Flags that catch trouble

Some flags change no code. -Wall -Wextra turn on warnings, and -Werror makes warnings fail the build, which Memfault calls “a must have” for keeping warnings out of the main branch. -Wdouble-promotion deserves a story. In C, a float that meets a double becomes a double. On a core with a single-precision FPU, double maths runs in slow software. Memfault shows a small example where fixing one promotion cut .text from 1,420 to 244 bytes, nearly 1,200 bytes saved by one warning. -fno-common turns two files that both define the same global into a build error, which is what you want. -fstack-usage writes the stack use of every function. The memory lesson, Where Memory Goes, uses it.

And --specs=nano.specs picks newlib-nano, a smaller C library. The Arm toolchain notes say it must be given to both the compile and the link steps. The nano printf has no %f unless you add -u _printf_float, and Chapter 5 shows what that costs.

Flip them yourself

Trade bytes for cycles

Pick a level, then switch the other flags on and off. The top bar is flash against the 128 KiB slot. The bottom bar is cycles for one pass of the control loop.

Illustrative model: -O0 scales your and the vendor code by 1.9, -O2 by 1.22, LTO by 0.9; garbage collection removes 12,800 bytes of unused HAL code; the double-promotion fix removes 1,176 bytes, the size Memfault measured in its own small example (1,420 to 244 bytes of .text). Cycles per loop (7,900 / 3,300 / 2,500, LTO ×0.91) are made up. Time assumes the STM32L476’s 80 MHz maximum clock. Measure real cycles with the DWT cycle counter.

Notice what the device shows. Going from -Os to -O2 costs about 12,870 bytes and buys about 800 cycles per loop. If the loop runs at 1 kHz on an 80 MHz core, 800 cycles are 10 µs out of a 1,000 µs period, a 1% gain. Is it worth 12,870 bytes? Maybe. But now it is a decision with numbers, not a habit.

When the optimiser exposes your bug

A last pattern. The firmware works at -O0 and fails at -O2. The symptom is a flag that never changes in a loop, or a register read that happens once instead of many times. The measurement is to build both and diff the assembly of the failing function. The cause is nearly always code that relied on something the C rules do not promise, such as a hardware register read without volatile (see Reset to main()). The fix is in the code. Lowering the level only hides the bug until the next compiler version.

On real hardware. On an STM32 Nucleo, build the same project at -Os and -O2. Read the text column of size for each. Then time one control-loop pass with the DWT cycle counter (DWT->CYCCNT) around the call. Write the byte cost and the cycle gain side by side.

You add -ffunction-sections -fdata-sections to the compile flags but the image does not shrink. What is missing?

Chapter 5

Hunting the Big Symbol

Use three commands to go from “the image grew” to a named function and a fix with a price

A doctor does not start with surgery. She starts with a thermometer, then a blood test, then a scan, and each test narrows the question. Size problems in firmware work the same way. You have a red build. Three cheap tests tell you where the bytes went, and only then do you choose a fix.

Test one: which column grew?

Run arm-none-eabi-size on the good image and the bad one. Compare the columns from Chapter 1. If text grew, code or constants grew. If data grew, a table lost its const. If bss grew, a buffer got bigger. One command, five seconds, and you have halved the search.

Test two: which symbols are big?

The tool nm lists the symbols in an image. Memfault notes that it can sort them by size. The command is:

arm-none-eabi-nm --size-sort --print-size --reverse-sort app.elf | head -8

Each line has an address, a size in hex, a letter and a name. The letter T means code in .text. The letter r means read-only data. A name like _svfprintf_r that you never wrote is a vendor or library function. Names in your own code are easy to spot.

Test three: who asked for it?

Now the map file. Search it for the library member and read its “included to satisfy reference by” line, as in Chapter 3. With --cref, search the cross-reference table for the symbol instead. Follow the trail until it reaches your own file. This is the moment the mystery ends: comms.c.o asked for snprintf.

Run the three tests on the gripper below. Then pick a fix and see its price.

Diagnose, then choose a fix

Press the three tests in order. Then choose a fix. Each bar is the image size at -O2 with that fix, against the 128 KiB slot line.

Press 1. size to start.

Illustrative: sizes follow the model in Chapter 4 at -O2. The nm lines and addresses are made up to match the map in Chapter 3. The price of nano with float (+10,200 bytes) and of an own formatter (+300 bytes) are placeholders: measure both in your own map, because the sources used here give no figure.

The four fixes, and what each one costs

Keep full newlib. Nothing in the code changes, and %f works exactly as the standard says. The price is +40,960 bytes, and in this project the build no longer fits. It also brings in malloc, so you must reserve heap space (Chapter 6).

Use nano and print integers. Pressure in the sensor is a whole number of hundredths of a kilopascal, so there is no real need for a float. Say p is 12,345, meaning 123.45 kPa. Print the whole part and the fraction as two integers:

/* p is in hundredths of a kPa: 12345 means 123.45 kPa */
uint32_t whole = p / 100;      /* 12345 / 100 = 123 */
uint32_t frac  = p % 100;      /* 12345 % 100 = 45  */
snprintf(buf, sizeof buf, "%lu.%02lu kPa", (unsigned long)whole, (unsigned long)frac);

The output is 123.45 kPa. No float is involved, so the nano printf is enough. The cost is zero extra bytes. It is also faster, since integer division on a Cortex-M4 takes few cycles.

Use nano with float printing turned on. The toolchain notes say float formatting in nano is a weak symbol, and you pull it in by adding -u _printf_float to the link flags (and -u _scanf_float for input). This keeps the smaller library but still brings in the float conversion code. The sources used for this lesson give no size for it. Measure it with your own two maps.

Write one small formatter. If you need one format in one place, a 20-line function beats a general library. It is also easy to test. You pay a few hundred bytes and you own the code.

Which is right? The question that decides is: “What do I actually need to print?” Most firmware prints a handful of fixed formats. The general-purpose printf is built for every format ever invented, and you pay for all of them. Choosing the narrow tool is the usual answer, and the map is the proof.

The second-biggest row

Look again at the nm list. The second line is not code. It is calib_table, a read-only array of 3,072 floats: 3,072 × 4 = 12,288 bytes. It was there before the new line, so it is not the culprit. But it is the next place to look when you need room, and the arithmetic is simple. If the calibration needs only 16 bits of precision, store the table as int16_t. Then it takes 3,072 × 2 = 6,144 bytes, and 6,144 bytes are free again. The cost is a little code to convert each value back to a float when it is read, and a check that the lost precision does not matter.

This is the ladder of savings, from cheapest to dearest. First remove what nobody calls (Chapter 4). Then choose narrower tools, such as integer printing. Then shrink the data. Only then think about giving up a feature, or about a bigger chip.

One more habit. When a fix works, write down the numbers: the size before, the size after, the symbol, the commit. Next quarter, someone will add a different line and cross the same boundary. A saved map and a two-line note make that fix a ten-minute job. The CI gate in Chapter 9 turns this habit into a rule.

On real hardware. On a Nucleo, run arm-none-eabi-nm --size-sort --print-size --reverse-sort build/app.elf | head -20 on your own project. Find the three biggest symbols. For each, answer: did I write it? If not, who asked for it?

The size command shows text grew by 40,960 bytes and data and bss did not change. What is the best next test?

Chapter 6

Flash and RAM Budgets

Plan the memory before you fill it, and see why a safe update scheme halves the room for your code

You rent a flat with a fixed number of cupboards. The landlord does not care what you own. Your belongings either fit or they do not. A microcontroller is a flat with two sets of cupboards: flash, which keeps its contents, and RAM, which does not. A budget is a plan, made in advance, that says how many cupboards each thing may use. Without one, the first feature to arrive late finds no room left.

The flash plan

The STM32L476RG has 1 MiB (1,024 KiB) of flash. Very few products give it all to the application. Part goes to the bootloader, a small program that starts first and decides whether to run the application or install a new one. Part goes to storage for settings and logs, which must survive power loss. And if the device can update itself in the field, a large part goes to a second copy.

The safest update design is dual slot (also called A/B). The device runs from slot A. A new image is written into slot B while A keeps running. Only when B is complete and checked does the bootloader switch. If the update fails halfway, A is untouched, and the device is not bricked. The price is plain: every image needs two slots. Lesson Bootloaders and OTA builds this scheme in full. For this chapter, only the arithmetic matters.

A worked example. Reserve 32 KiB for the bootloader and 64 KiB for storage. That leaves 1,024 − 32 − 64 = 928 KiB. With a single slot, the application may use 928 KiB. With dual slots, each slot gets 928 / 2 = 464 KiB. The room for your code has been cut in half by a decision that has nothing to do with your code.

So a size budget has two numbers. The first is the hard limit: the slot size, enforced by the linker with the LENGTH from Chapter 2. The second is a soft limit, a team rule that fires before the hard one. A common soft limit is to keep 10% of the slot free, which is a habit of teams and not a standard. It leaves space for the bug-fix release that you cannot predict.

The RAM plan, and what the linker cannot see

RAM has four users. Static data is .data plus .bss: the linker knows its exact size. The heap is memory that code asks for while running, with malloc. The stack holds the local variables and return addresses of the functions that are running right now. Each grows while the program runs, so the linker cannot know their final size.

What does the linker do about heap and stack? Not much. It checks that the static data fits. ST’s generated linker scripts add two symbols, _Min_Heap_Size and _Min_Stack_Size, and make the build fail if the space left over is smaller than their values. That is a floor you set by hand. The linker cannot measure the real peak, so the number is your estimate.

Here is the failure that follows. The static data is 49,104 bytes in a 96 KiB (98,304 byte) RAM. The linker says everything fits. But the heap and stack grow into the leftover space. Take away the 4 KiB stack and an 8 KiB heap, and 36,912 bytes remain. That is still fine. Now let the replay buffer grow by 40 KiB for a new feature. The static data hits 90,064 bytes, and the stack and heap of 12 KiB together no longer fit. Depending on the layout, the stack grows down into the buffer, and the next deep function call silently overwrites the first bytes of the buffer. The symptom is a buffer that fills with garbage once in a thousand runs. No tool reports it.

The measurement that catches this is to fill the stack area with a known pattern at start-up and later look for how much of the pattern is gone. The memory lesson Where Memory Goes does this, and adds a hardware guard with the MPU. The fix is to make the budget explicit: set _Min_Stack_Size to the measured peak plus a margin, keep static data below the remainder, and let the build fail when it does not.

Plan one yourself

Split the flash and the RAM

Top: the 1,024 KiB flash with a 32 KiB bootloader and 64 KiB of storage. Bottom: the 96 KiB RAM. Choose the update scheme, then move the sliders.

94
48
0
4

Illustrative plan: 32 KiB bootloader and 64 KiB storage are the lesson’s own choices. The 10% soft limit is a common team rule, not a standard. The 1 MiB of flash and the 96 KiB of RAM at 0x20000000 are the STM32L476RG figures from ST’s linker script (the chip has a separate 32 KiB SRAM2 that this plan leaves out).

Try this sequence. Leave the scheme at dual slot and drag the image up. Around 464 KiB the slot is full and the bar turns red. Now switch to single slot: the same image fits, with 928 KiB of room. Switch back and notice how fast the room disappears. Then in the RAM bar, grow static RAM to 90 KiB with an 8 KiB heap and a 4 KiB stack. The bar runs out, and the read-out says by how many bytes.

On real hardware. Build with -Wl,--print-memory-usage and note the flash and RAM percentages. Then fill the stack area with a pattern at start-up, run your longest scenario for a minute, and count how many pattern words survive. Write down the peak stack depth in bytes next to the linker’s numbers.

A 1,024 KiB part reserves 32 KiB for a bootloader and 64 KiB for storage. How big can an application image be with dual-slot (A/B) updates?

Chapter 7

CMake and the Toolchain File

Put every flag in one place so that your laptop, your teammate’s laptop and the CI server all run the same commands

Five people work on the gripper. Ana builds in an IDE. Ben types a make command from a note he saved. The CI server runs a third script. Each has a slightly different list of flags. Ana’s build passes. The CI build fails with a linker error that nobody else can repeat. The bug is not in the code. It is that there are three builds.

A build system fixes this by holding the build in one description that everyone uses. CMake is the most common choice for C and C++ firmware today. It does not compile anything itself. It reads your description and writes the build files for a faster tool, often Ninja or Make. Memfault’s article on a modern C environment uses CMake for exactly this reason, with two commands to build: cmake -B build and cmake --build build.

Why a toolchain file

CMake assumes by default that you build for the computer you are using. For firmware you do not. You need to tell CMake three things: the compiler is a cross compiler, the target has no operating system, and the test programs it runs at the start cannot be linked the usual way. These facts live in a separate small file, the toolchain file. You pass it once with -DCMAKE_TOOLCHAIN_FILE=path/to/file, and the CMake manual says: “the file will be loaded early to set values for the compilers.”

Three lines in it do the heavy lifting. CMAKE_SYSTEM_NAME Generic: the CMake manual says, in its Renesas example, that it “must be specified to enable cross compiling”, and Generic is the value CMake uses for a target with no operating system, which is what bare-metal firmware is. CMAKE_C_COMPILER arm-none-eabi-gcc names the cross compiler. And CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY, which the manual uses “to tell CMake not to try to link executables during its checks”. At the start, CMake builds a tiny test program to see whether the compiler works. A bare-metal link needs a start-up file and a linker script that CMake does not have yet, so that test would fail. Asking for a static library skips the link.

# cmake/arm-none-eabi.cmake
set(CMAKE_SYSTEM_NAME      Generic)       # no operating system: a cross build
set(CMAKE_SYSTEM_PROCESSOR arm)
set(CMAKE_C_COMPILER      arm-none-eabi-gcc)
set(CMAKE_ASM_COMPILER    arm-none-eabi-gcc)
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)  # do not link in the configure tests
set(MCU_FLAGS -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard)

The four MCU_FLAGS describe the chip. -mcpu=cortex-m4 picks the core. -mthumb asks for the Thumb instruction set, the only one a Cortex-M runs. -mfpu=fpv4-sp-d16 names the single-precision floating-point unit. -mfloat-abi=hard passes floats in the FPU’s registers. These must be the same at compile time and at link time, because the linker picks the right C library variant from them.

The project file

Now the CMakeLists.txt says what to build and with which flags. Each flag from Chapter 4 has a home:

cmake_minimum_required(VERSION 3.20)
project(gripper C ASM)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)         # for clang-tidy and editors

add_executable(app.elf src/main.c src/pid.c src/comms.c startup_stm32l476xx.s)
target_compile_options(app.elf PRIVATE ${MCU_FLAGS}
  -Os -g3 -Wall -Wextra -Werror -Wdouble-promotion -fno-common
  -ffunction-sections -fdata-sections --specs=nano.specs)
target_link_options(app.elf PRIVATE ${MCU_FLAGS} --specs=nano.specs
  -T${CMAKE_SOURCE_DIR}/gripper.ld
  -Wl,-Map=${CMAKE_BINARY_DIR}/app.map,--gc-sections,--print-memory-usage)
add_custom_command(TARGET app.elf POST_BUILD
  COMMAND arm-none-eabi-size $<TARGET_FILE:app.elf>)

You build with cmake -B build -DCMAKE_TOOLCHAIN_FILE=cmake/arm-none-eabi.cmake and then cmake --build build. Every flag is in one file, in version control, and reviewed like code. The CI runs the same two commands. Ana’s IDE can read the same project. The three builds are now one build.

One gotcha worth a sentence. CMake has a setting, CMAKE_BUILD_TYPE, that adds its own flags per configuration. For GCC, a Release build typically adds -O3, which is not what you want on a small chip. Check your own CMakeCache.txt, and set the flags you mean, so that they do not depend on a hidden default.

Break the build on purpose

The fastest way to learn what each line does is to remove it. In the device below, switch off the lines one at a time. The four boxes are the four stages of a build. The first red box tells you where the trouble starts.

Remove a line, find the failure

All six lines start on. Switch one off and read what the build does. Then switch it back on and try another.

The behaviours are the standard ones: CMake’s configure test cannot link a bare-metal program; a Cortex-M cannot run Arm-state code; the linker refuses to mix hard-float and soft-float objects. The exact wording of the messages varies by tool version, so the box shows their meaning in plain words.

Notice one more thing. Turning off the map flag breaks nothing. The build is green. You lose a record you will need later, and nothing warns you. Silent losses like this are why the CI in Chapter 9 checks that the map exists.

When the IDE builds and the server does not

Here is the failure that pushes teams to CMake. The symptom: a change builds on one laptop and fails in CI, or builds in CI and fails on a second laptop. The measurement: run both builds with verbose output and compare the real compile and link lines word by word. The difference is nearly always one flag or one include path that lived in a private IDE setting. The fix: move it into the project file, so that there is no private setting left.

Two small habits help. Build in a separate folder (-B build), so that generated files never mix with your source and you can delete the folder to get a clean build. And treat a flag change like a code change: review it, because a changed flag can change the image as much as a changed line.

On real hardware. Take any Nucleo project and move its flags into a toolchain file and a CMakeLists.txt like the ones above. Build it. Then run cmake --build build --verbose and compare the real compile line with your intent. Check that the four -m flags appear on the link line too.

CMake's configure step fails with "the C compiler is not able to compile a simple test program" on a bare-metal ARM project. Which toolchain line is the usual cure?

Chapter 8

The Same Bytes, Every Time

Find the five quiet ways a build differs between two machines, and close each one

On Monday you build release 2.4 and ship it to a hundred robots. On Friday one of them faults in the field. You need to look at exactly the code that is running there, with symbols. You check out the tag and build again. The new image has a different hash from the one you shipped. Is it the same code? You cannot tell. You cannot trust the symbols from this build to explain the fault in that one.

A build is reproducible when the same source and the same tools always give the same bytes, on any machine, on any day. Memfault’s article gives three reasons it matters: “It’s hard to debug a problem when you can’t reproduce it yourself!”, it lets you recreate the debug symbols for an image whose symbols were not kept, and open source projects also want it for security.

How a build leaks the machine it ran on

A compiler is a program like any other. If its output depends on something other than your source, then two machines give two images. Memfault’s article names three leaks below: absolute paths, include order and the compiler version. The GCC manual covers the fourth, the date. Here they are, each with an example.

Absolute paths in __FILE__. The macro __FILE__ expands to the path by which the preprocessor opened the file. An assert macro often prints it. On Ana’s laptop the string is /home/ana/gripper/src/pid.c. On Ben’s it is /Users/ben/work/gripper/src/pid.c. The strings differ, and so do their lengths. Ana’s path has 27 characters, Ben’s has 33. That shifts everything that comes after the string in .rodata by six bytes, and the image changes in many places, not only one.

Absolute paths in debug info. The same paths end up in the DWARF debug sections of the .elf. The article says the GNU Build ID, a hash that identifies the image, covers the binary sections and the debug sections. So a path difference changes the Build ID even when the code bytes match.

The date and time. The GCC manual says __DATE__ “expands to a string constant that describes the date on which the preprocessor is being run”, and __TIME__ does the same for the time. A version string built from them changes every minute. No two builds can match.

Include order. Memfault describes a case where reordering the -I paths changed which config.h the compiler found first. That changed one macro, and so the code.

Compiler version. Different compiler versions make different code from the same C. The article's fix is a Makefile check that stops the build if the version differs from an expected one.

The fixes

Each leak has a plain fix. For paths, use -ffile-prefix-map=old=new. The GCC manual says that when compiling files in directory old, it records any references to them “as if the files resided in directory new instead”. With -ffile-prefix-map=/home/ana/gripper=., the string is ./src/pid.c on every machine. (Memfault adds that the flag may not reach the assembler in some GCC versions, so they also pass -Wa,--debug-prefix-map.)

For the date, stop using __DATE__ and __TIME__. Pass the git commit to the compiler, for example -DGIT_SHA=\"a1b2c3d\". A commit is a better version stamp than a time. The reproducible-builds project also defines SOURCE_DATE_EPOCH as a standard variable holding a fixed “last modification” time in seconds since the Unix epoch. Check that your compiler honours it before you rely on it.

For the compiler and the include order, pin them: build in a container that holds one compiler version, and keep include paths in one place (the CMake file from Chapter 7). Chapter 9 puts this into CI.

Run the checker

The device below builds the same source on two machines. Switch the leaks on and see the two hashes split. Then switch the fixes on and watch them rejoin. The hashes are real, computed in your browser from the toy image; only the image itself is a model.

Do the two machines agree?

Machine A builds in /home/ana. Machine B builds in /Users/ben, a few minutes later, with a newer compiler. First switch on leaks. Then switch on fixes.

A toy image: three parts (code, strings, debug info) are built as text from the switches, then hashed with a small 32-bit checksum (FNV-1a). Real images are megabytes and real hashes are SHA-256; the lesson is which inputs reach which part. Following Memfault, the Build ID covers the binary and the debug sections, and the debug sections are not flashed to the chip.

Two details in the device repay a second look. First, with only the path leak on, the flashed bytes and the Build ID both change. With only the debug-path leak, the flashed bytes match but the Build ID does not, so a hash of just the .bin can pass while the .elf you need for symbols has drifted. Check both. Second, the date is the worst offender because it can never be pinned down. You must remove it.

On real hardware. Build your project in two different directories (copy the repo to /tmp/a and /tmp/b). Run sha256sum build/app.bin in each. If they differ, run arm-none-eabi-readelf -n build/app.elf to compare the Build ID, and arm-none-eabi-strings -d build/app.elf -n 10 to look for absolute paths, the commands Memfault uses. Fix one leak at a time.

Two builds of the same commit have identical .bin files but different GNU Build IDs. What is the most likely cause?

Chapter 9

CI and the Size Gate

Let a robot run the same build on every change, and fail it when the image grows too much or drifts from the last one

A teammate adds one line on Friday afternoon. It builds on his laptop, and he goes home. By Monday the image is 40 KB bigger, three more changes sit on top of it, and nobody knows which one did it. The fix is to ask the question at the moment of the change, while only one line is under suspicion. Continuous integration (CI) is a server that runs your build and checks on every push, before anyone reviews the change.

Make the build the same everywhere first

CI only helps if the server builds like you do. Chapters 7 and 8 gave you the tools. Memfault’s modern C environment article shows the pattern: build inside a Docker image so that every machine, including the CI server, uses the same tools. It pins the base image to a tag (they use bullseye), because the packages vary between base images. It pins the platform with --platform linux/amd64. And it pins the LLVM version so that the formatting and analysis tools match their config files.

It also keeps the CI fast. The image is cached, and the cache key comes from the hash of the Dockerfile: key: ${{ runner.os }}-docker-${{ hashFiles('builder.Dockerfile') }}. The key changes only when you change the Dockerfile, so the image is rebuilt only when it should be. The pipeline runs on every push to main and on a weekly timer (cron: '0 1 * * 0', every Sunday at 01:00). The weekly run catches the day a tool you did not pin changes under you.

The gates

A gate is a check that must pass before a change can merge. A firmware pipeline usually has these, in order of cost, cheapest first.

Gate 1, the build with warnings as errors. The flags from Chapter 4 (-Wall -Wextra -Werror) turn a new warning into a red build. This is the check Memfault calls “a must have” for keeping warnings out of main.

Gate 2, the size gate. A short script reads arm-none-eabi-size for the new image and compares it to numbers saved from main. It enforces three rules. The hard limit is the slot size from Chapter 6: above it, the linker would already fail. The soft limit is the 10% headroom rule: above it, the change needs a human to approve. The delta limit caps the growth of one change, say 2,048 bytes. That third rule is the clever one. It catches the table that lost its const, which adds 8 KiB yet keeps the total well under the hard limit.

Gate 3, the reproducibility check. Build twice, in two different folders, and compare the hash. A change that adds __DATE__ turns this gate red on the day it is written, when the cause is one line away.

Gate 4, keep the evidence. Upload the .map and the .elf as artifacts. When the size gate fires, the first thing a reviewer needs is the map of this build and the map of main. Memfault notes that GitHub’s free plan includes “500 MB of storage” for artifacts, so they set a short retention (retention-days: 3) and use caches for big files. Keep release maps for much longer, in a place you choose.

A worked example of the size gate. Main is 96,258 bytes. The hard limit is 131,072. The soft limit is 90% of that, 117,964. The delta limit is 2,048. A change adds the full-newlib float printf: +40,960 bytes, for a total of 137,218. It is above the hard limit, and above the delta limit too. The gate prints both and fails. The message names the numbers, so the author does not need to guess.

Try the gates

Send a change through the gates

Pick a change. The five boxes are the gates, left to right. The graph shows the last twelve builds of main and your change as the last point. Move the delta limit to see the trade-off.

2,048

Illustrative: main’s history (about 94 to 96 KB, from the gripper model at -O2 with nano printf), the changes and their sizes are made up, except that the full-newlib float printf adds the 40,960 bytes of the Chapter 3 map. The 128 KiB hard limit, the 90% soft limit and the delta limit are this project’s own policy, not standards.

Try the table without const. It adds 8,192 bytes of flash and 8,192 bytes of RAM. It stays below both size limits. Only the delta limit catches it. Now drag the delta limit up to 8,192: the gate passes, and the table ships. A gate is a policy, and the number is yours to set. Set it by looking at the growth of your last twenty merged changes: a limit that is never hit teaches nothing, and one that fires every day is ignored.

On real hardware. Pick any firmware repo that builds with CMake. Add a CI job that runs the two commands from Chapter 7 in a pinned container, prints arm-none-eabi-size, and fails if text + data goes over your slot. Push a change that adds a large const table and watch the job go red.

A change adds a lookup table without const: +8 KiB flash and +8 KiB RAM. Total flash stays under the hard and soft limits. Which gate catches it?

Chapter 10

The Field Guide

Keep the numbers, the checklist and the core code from this lesson on one page

One C line asked a library for help, and the linker packed in forty kilobytes of it. You now have the tools to see that. The compiler sorts your program into four sections. The linker joins them, places them as the script says, and writes a map of every choice. The flags set the trade between bytes and cycles. A budget turns “it fits today” into a rule. CMake keeps every flag in one file, a pinned container keeps the tools fixed, and CI checks all of it on every change.

Numbers and terms

ItemValue or meaningWhere it comes from
.text, .rodataCode and read-only data. Both live in flash.binutils size manual: read-only data counts in the text column
.dataVariables with a starting value. Cost flash once and RAM once.GNU ld: load address set by AT>
.bssZero-start variables. Cost RAM only.C rules; start-up code zeroes it
size columnsdec = text + data + bss. Flash = text + data. RAM = data + bss.binutils size manual
A real size line1704 / 108 / 28 / 1840 for a nRF52840 buildMemfault Interrupt, linker map file article
A real overflowtext 2,256 into 0x800 (2,048) gives overflowed by 208 bytesMemfault Interrupt, linker map file article
-O0 / -O2 / -OsDefault and debuggable / nearly all optimisations without a space-speed trade / optimise for sizeGCC manual, Optimize Options
-Wdouble-promotionOne fix cut .text from 1,420 to 244 bytes in a small exampleMemfault Interrupt, GCC flags article
--gc-sectionsDrop input sections that nothing references. Needs -ffunction-sections and -fdata-sections to bite.GNU ld manual; Memfault GCC flags article
-Wl,-Map=fileWrite the link map to a fileGNU ld manual; Memfault map file article
-ffile-prefix-map=old=newRecord paths under old as if they were under newGCC manual, Overall Options
STM32L476RG1 MiB flash at 0x08000000, 96 KiB RAM at 0x20000000ST linker script as quoted in Reset to main()
The gripper numbers128 KiB slot, +40,960 bytes for full printf, 96,258 bytes at -O2Illustrative model of this lesson

The checklist

  1. Write a map file in every build, and keep the map of every release.
  2. Give the flash and RAM regions a hard LENGTH in the linker script.
  3. Add -ffunction-sections -fdata-sections to compile and -Wl,--gc-sections to link.
  4. Put const on every table that never changes, and check the data column of size.
  5. Pass the same -m flags and the same --specs to compile and link.
  6. Turn on -Wall -Wextra -Werror -Wdouble-promotion -fno-common.
  7. Keep every flag in a toolchain file and a CMakeLists.txt, in version control.
  8. Build in a pinned container. Stamp the version with a git SHA, never __DATE__.
  9. Use -ffile-prefix-map, and test reproducibility by building in two folders.
  10. In CI, gate on a hard limit, a soft limit and a delta limit, and keep the map as an artifact.

The core as code

This is the size gate from Chapter 9. It reads arm-none-eabi-size, checks the three limits, and prints numbers a reviewer can act on.

#!/usr/bin/env python3
# size_gate.py: fail the build when the image is too big or grew too fast
import json, subprocess, sys

def measure(elf):
    row = subprocess.check_output(["arm-none-eabi-size", elf], text=True).splitlines()[1].split()
    text, data, bss = map(int, row[:3])
    return text + data, data + bss          # flash bytes, static RAM bytes

elf, base_json = sys.argv[1], sys.argv[2]
HARD, SOFT, DELTA = 131072, 0.9 * 131072, 2048
flash, ram = measure(elf)
base = json.load(open(base_json))["flash"]
grew = flash - base
print(f"flash {flash} B, was {base} B, delta {grew:+d} B, slot {HARD} B")
fails = []
if flash > HARD: fails.append(f"over the slot by {flash - HARD} B")
elif flash > SOFT: fails.append("above the 90% soft limit: needs approval")
if grew > DELTA: fails.append(f"grew by {grew} B, limit {DELTA} B: open the map diff")
for f in fails: print("FAIL:", f)
sys.exit(1 if fails else 0)

And the four commands that make a build you can trust, run from the repository root:

cmake -B build -DCMAKE_TOOLCHAIN_FILE=cmake/arm-none-eabi.cmake
cmake --build build
arm-none-eabi-size build/app.elf
arm-none-eabi-nm --size-sort --print-size --reverse-sort build/app.elf | head

Keep going

The build is the floor under every other firmware skill. Next, First Light uses it to bring up a board from nothing. Where Memory Goes measures the stack and heap that the linker cannot see. Bootloaders and OTA builds the dual-slot scheme that halved your room in Chapter 6. Seeing Inside a Running Chip uses the map and the .elf to name a crashing address. Test Firmware Without the Board adds tests to the CI from Chapter 9. Behind them sit the C basics in Embedded C and Advanced C, and the start-up story in Reset to main().

Sources

This lesson has no slides. It is built from primary sources opened for it, listed here. Memfault Interrupt: Get the most out of the linker map file; The Best and Worst GCC Compiler Flags For Embedded; A Modern C Development Environment; Reproducible Firmware Builds. Manuals: GCC Optimize Options, GCC Overall Options, cpp Predefined Macros, GNU ld Options, ld Output Section LMA, binutils size, CMake toolchains, and SOURCE_DATE_EPOCH. The newlib-nano flags (--specs=nano.specs, -u _printf_float) come from the GNU Arm Embedded Toolchain readme, read through mirrors of its 2014 to 2016 releases, so check them against your toolchain version.

Credit: the structure of the map-file reading, the flag advice, the container pattern and the reproducibility checks follow the Memfault Interrupt articles above, re-taught here in our own words with our own devices and our own illustrative numbers.

The takeaway. The build is part of the firmware. Write the map every time, set hard limits, keep every flag in one file, build in a pinned container, and let CI say no first.
Which sequence best describes how to answer “why did the image grow by 40 KB?”

Open Present to explain the pipeline back in your own words, or Teach to draw it on a whiteboard. Then go back to the instrument and find which setting lets full printf fit.

Compiler, Linker and the Map File
Memfault Interrupt · Back to Gleams