</>EmbeddedInterview

How do you reduce firmware code size?

MediumDebugging, Testing & Tools

Short answer: Measure first (map file, nm --size-sort, bloaty), then: compile with -Os (or -Oz with Clang), enable -ffunction-sections -fdata-sections with -Wl,--gc-sections so unused functions are removed, use link-time optimisation (-flto), use newlib-nano (--specs=nano.specs) and avoid heavy library functions (printf with floats, sscanf, iostream), remove unused vendor HAL code or switch to LL/register-level drivers, move constant tables to compact formats, and avoid code duplication from macros and templates.

Techniques ranked by typical impact

Technique Typical saving
Remove floating-point printf/scanf, use integer formatting 10–20+ KB
--gc-sections with function/data sections large if libraries are linked whole
-Os vs -O2 10–30% of code
LTO 5–15% (cross-module inlining, dead code removal)
newlib-nano several KB
Replace vendor HAL with LL drivers often 10–30 KB in HAL-heavy projects
Thumb-2 (default on Cortex-M) vs ARM state on Cortex-A/R ~25–30%
Compress assets (fonts, images), store tables as const depends
Avoid inline expansion of large macros/inline functions in many places depends
Logging with IDs instead of strings (deferred logging) string data

Be careful: size optimisation can make code slower (-Os disables some loop unrolling) — keep hot paths fast with function attributes (__attribute__((optimize("O2"))) sparingly) or by placing them in RAM; aggressive optimisation can expose latent undefined behaviour, so run the full test suite on the optimised build.

RAM reduction: check .bss and .data in the map file, size stacks from measured high-water marks, shrink buffers to measured needs, use const so tables stay in flash, and share buffers between features that never run at the same time (unions or overlays, carefully).