Try Embedded

C++ embedded constraints and the STL

No heap, no exceptions, no RTTI: the C++ that fits a microcontroller.

The rules change on a microcontroller

Desktop C++ assumes a large heap, an operating system that cleans up after crashes, and nobody counting kilobytes. A microcontroller with 64 KB of RAM and a hard real-time deadline breaks all three assumptions. Embedded C++ is the same language with a set of features switched off or used with care.

FeatureTypical embedded policyWhy
Heap (new, std::vector growth)Forbidden after start-up, or entirelyFragmentation, unbounded time, out-of-memory with no recovery
ExceptionsDisabled with -fno-exceptionsUnwind tables cost flash; throw time is unbounded
RTTI (dynamic_cast, typeid)Disabled with -fno-rttiType information for every polymorphic class
iostreamNeverPulls in tens of kilobytes and static constructors
TemplatesAllowed, watch flashEvery instantiation is new code
constexpr, enum class, references, RAIIEncouragedZero cost, catch bugs at compile time

Living without the heap

Dynamic allocation is not banned because it is slow; it is banned because it can fail at an unpredictable moment, after weeks of uptime, when the heap has fragmented. A device that must run for years allocates everything up front.

Options, from strictest to loosest:

  1. Static allocation only. Every object is a global, a static, or on the stack. Sizes are fixed at compile time. The linker map tells you exactly how much RAM is used.
  2. Allocate at start-up only. new is allowed during initialisation, then forbidden. Some projects enforce this by making operator new fault after a flag is set.
  3. Fixed-size pools. Blocks of one size, allocated and freed in constant time with no fragmentation.

Containers with fixed capacity replace the standard growing ones. The Embedded Template Library (ETL) provides etl::vector<T, N>, etl::string<N>, etl::queue<T, N> and others that keep their storage inside the object:

etl::vector<Reading, 32> history;   // storage for 32 elements, no heap
if (!history.full()) history.push_back(r);

std::array<T, N> is always safe: it is a C array with size() and bounds-checked at().

Living without exceptions

With -fno-exceptions, throw does not compile and library code that would throw calls std::abort instead. Errors become values:

enum class Status { ok, timeout, nack, bus_error };

Status I2c::write(uint8_t addr, std::span<const uint8_t> data);

if (auto s = bus.write(0x48, cfg); s != Status::ok) {
  log_error(s);
}

C++23 adds std::expected<T, E>, which carries either a value or an error. Many embedded projects use a small hand-written equivalent or ETL's etl::expected.

Pitfall: [[nodiscard]] on functions that return a status makes the compiler warn when a caller ignores the result. It is free and catches a whole class of bugs.

What is safe from the standard library

Header-only, allocation-free parts are generally fine:

  • <array>, <span> (C++20), <optional>, <variant>, <bitset>
  • <algorithm> on fixed buffers: std::sort, std::find, std::min, std::clamp
  • <cstdint>, <limits>, <type_traits>, <utility>, <atomic> (if the core supports the operations)

Avoid or check carefully: <string>, <vector>, <map>, <functional> (std::function may allocate), <iostream>, <regex>, <thread> without an RTOS port.

Keeping the binary small

  • Build with -Os or -O2, plus -ffunction-sections -fdata-sections and link with --gc-sections so unused functions are dropped.
  • Use -fno-threadsafe-statics if function-local statics are only initialised from one context; otherwise each one gets a lock.
  • Link with --specs=nano.specs (newlib-nano) for a smaller C library.
  • Read the map file after adding a template or library: a surprise 20 KB is easy to spot early.

Interrupts and C++

An interrupt handler must have C linkage so its name matches the vector table:

extern "C" void USART2_IRQHandler() {
  uart2.on_interrupt();   // forward into the object
}

Keep the object global (or a static member) so the handler can reach it, and keep the handler short.

Interview question: Your team wants to use std::vector in firmware. What do you say?

Answer: The problem is the heap, not the vector. A std::vector that grows calls new, which can fragment the heap and fail at run time with no good recovery. If the size is known, use std::array. If it varies up to a bound, use a fixed-capacity container such as etl::vector<T, N>, which keeps its storage inline. If a std::vector is really wanted, reserve its full capacity during initialisation and never let it grow afterwards, and enforce that.

Interview question: How do you handle errors in embedded C++ without exceptions?

Answer: Return them as values: an enum class status code marked [[nodiscard]] so callers cannot silently ignore it, or an expected/optional-style type that carries either a result or an error. Unrecoverable conditions (a broken invariant) go to an assert or fault handler that logs and resets, usually via the watchdog.

Going deeper

Interview question: Which C++ features would you allow in a hearing aid's firmware, and which not?

Answer: Allow classes, templates, constexpr, RAII, namespaces and enum class, which cost nothing at run time. Forbid exceptions and RTTI (code size and unpredictable timing), heap allocation after start-up, and STL containers that allocate; use fixed-capacity containers instead. Enforce it with compiler flags (-fno-exceptions, -fno-rtti) and a coding standard so it cannot creep back in.

Interview question: How can you make sure no code calls the heap after start-up?

Answer: Provide your own operator new and malloc (or hook the allocator) that work only while an initialisation flag is set and fault with a clear message afterwards; link with --wrap=malloc to intercept library calls; and check the map file for allocator functions being pulled in. Static analysis rules and code review catch direct uses, and containers with fixed capacity remove the main reason to allocate.

Interview question: What is the cost of a function-local static object in C++, and how can it be reduced?

Answer: The compiler must ensure it is constructed exactly once, even if two threads reach it together, so it adds a guard variable and, with threading support, calls to a lock (__cxa_guard_acquire). On single-threaded firmware, -fno-threadsafe-statics removes the locking. Making the object constexpr-constructible or a plain global avoids the guard entirely.

Explain it: In your own words, explain why exceptions are usually disabled in embedded C++ and what replaces them.

Answer: Exception support needs unwind tables and runtime code, which cost a significant amount of flash, and throwing takes a time that is hard to bound, which conflicts with real-time deadlines; many safety standards also restrict them. So projects compile with -fno-exceptions and report errors as values instead: status enums marked nodiscard, or types such as expected or optional that carry either a result or an error. Truly unrecoverable conditions go to an assert or fault handler that logs and resets.