On a desktop, a few microseconds spent building a lookup table at startup is nothing. On a microcontroller with 32 KB of flash and 2 to 4 KB of RAM, the same table can cost RAM you can’t spare, a slower boot, and code that has to run before your first interrupt is enabled. Modern C++ lets you move that work to the compiler, so the firmware ships with the finished result.

This article walks through how constexpr, consteval and constinit help on small MCUs. Every example is self-contained: it carries its own headers and compiles on its own.

Assumptions. Every example targets C++20 (consteval and constinit need it) and was built with GCC 13.3 using -std=c++20 -O2 -Wall -Wextra, with every static_assert passing. The section placement shown later comes from ARM GCC 11.2.1 (arm-none-eabi), Xtensa ESP32 GCC 14.2.0 and AVR GCC 14.3.0, all at -O2; the exact commands are in that section. Older toolchains, or a project set to C++17, will reject consteval and constinit.

Why compile-time computation matters on small MCUs

Three resources are tight on almost every microcontroller:

Flash holds your code and constant data. It is usually the largest memory on the chip.

RAM holds variables, the stack and the heap. It is often eight to sixteen times smaller than flash.

Startup time matters for battery devices that wake, measure and sleep, and for anything that must react quickly after reset.

A table filled at runtime needs code to build it, RAM to hold it, and cycles at boot. A table the compiler computes needs only storage for the finished data. Where that storage ends up (flash, or a RAM copy) depends on the toolchain and the linker script, and the last section shows how to check it.

constexpr basics

A constexpr variable must be initialised with a value the compiler can work out. A constexpr function can be evaluated by the compiler when its arguments are known at compile time, and still runs normally at runtime when they are not. For a refresher on the rules, including the difference between const, constexpr and static constexpr, Cpp Next has a clear guide to constexpr variables and functions.

#include <cstdint>

constexpr std::uint32_t sysclk_hz    = 16'000'000;
constexpr std::uint32_t ticks_per_ms = sysclk_hz / 1000;  // computed by the compiler

Since C++14, constexpr functions may contain loops, local variables and branches, which is what makes real tables possible.

Lookup tables built at compile time

A CRC-8 table, checked against its standard check value

The table-driven CRC is fast, but its table has 256 entries. Here the compiler generates it for the polynomial 0x07 (initial value 0, no reflection, no final XOR):

#include <array>
#include <cstddef>
#include <cstdint>

constexpr std::array<std::uint8_t, 256> make_crc8_table(std::uint8_t poly) {
    std::array<std::uint8_t, 256> table{};
    for (int i = 0; i < 256; ++i) {
        auto crc = static_cast<std::uint8_t>(i);
        for (int bit = 0; bit < 8; ++bit)
            crc = (crc & 0x80) ? static_cast<std::uint8_t>((crc << 1) ^ poly)
                               : static_cast<std::uint8_t>(crc << 1);
        table[i] = crc;
    }
    return table;
}

constexpr auto crc8_table = make_crc8_table(0x07);

constexpr std::uint8_t crc8(const char* data, std::size_t len) {
    std::uint8_t crc = 0x00;
    for (std::size_t i = 0; i < len; ++i)
        crc = crc8_table[crc ^ static_cast<std::uint8_t>(data[i])];
    return crc;
}

static_assert(crc8("", 0) == 0x00);
static_assert(crc8("123456789", 9) == 0xF4, "CRC-8 check value");

Checking one table entry proves little. The second assertion runs the whole algorithm over the standard nine-byte check string and compares it with the published check value for this CRC, 0xF4. That catches the common mistakes, such as a wrong polynomial, a bit-order slip or a wrong initial value, because each of them changes the result and fails the build. One check vector is a smoke test, not a proof: it cannot show that every entry of the table is right. For that, compare the generated table with a trusted reference implementation over all 256 inputs, which a host-side unit test does in a few lines.

A quarter-wave sine table, checked over every entry

std::sin is not usable in a constant expression in C++20. C++26 makes much of constexpr, but whether a given compiler and standard library support it yet varies, so a small Taylor series is the portable choice:

#include <array>
#include <cstddef>
#include <cstdint>

constexpr double pi = 3.14159265358979323846;

constexpr double taylor_sin(double x) {
    double term = x, sum = x;
    for (int n = 1; n < 8; ++n) {
        term *= -x * x / ((2 * n) * (2 * n + 1));
        sum += term;
    }
    return sum;
}

template <std::size_t N>
constexpr std::array<std::int16_t, N> make_sine_q15() {
    std::array<std::int16_t, N> t{};
    for (std::size_t i = 0; i < N; ++i) {
        double angle = (pi / 2) * static_cast<double>(i) / (N - 1);
        t[i] = static_cast<std::int16_t>(taylor_sin(angle) * 32767.0 + 0.5);
    }
    return t;
}

template <std::size_t N>
constexpr bool sine_table_ok(const std::array<std::int16_t, N>& t) {
    for (std::size_t i = 1; i < N; ++i)
        if (t[i] <= t[i - 1]) return false;               // strictly rising
    for (std::size_t i = 0; i < N; ++i) {                 // sin² + cos² = 1
        std::int64_t s = t[i], c = t[N - 1 - i];
        std::int64_t err = s * s + c * c - static_cast<std::int64_t>(32767) * 32767;
        if (err < 0) err = -err;
        if (err > 2LL * 32767) return false;                // about one LSB
    }
    return t[0] == 0 && t[N - 1] == 32767;
}

constexpr auto sine_q15 = make_sine_q15<64>();
static_assert(sine_table_ok(sine_q15));

The check looks at every entry, not only the endpoints. The table must rise strictly, start at 0, end at 32767, and every pair of entries a quarter-wave apart (sin and cos of the same angle) must satisfy sin² + cos² = 1 to within about one least significant bit. Those invariants catch gross errors such as a wrong scale, a wrong step or a bad series term. They do not prove each sample’s accuracy on their own: a table could pass them and still be slightly off at some angles. That is what the host test is for. On the host, each of the 64 entries was compared with std::lround(std::sin(angle) * 32767.0), and all 64 matched exactly.

The floating-point maths happens only inside the compiler. The firmware contains 64 integers and no floating-point code, which matters on cores without an FPU.

Checking peripheral configuration with static_assert

Many configuration mistakes are arithmetic: a baud rate divisor that rounds badly, a prescaler that overflows its register, a PLL setting out of range. All of them can be checked before the code reaches the board. This example repeats the clock from the first one so that it compiles on its own:

#include <cstdint>

constexpr std::uint32_t sysclk_hz = 16'000'000;   // the same clock as the first example

void invalid_uart_setting();   // deliberately not constexpr: reaching it fails the build

// Supported inputs: clock_hz and baud are any 32-bit values with baud > 0.
// The sum is formed in 64 bits, so it cannot overflow.
constexpr std::uint32_t uart_divisor(std::uint32_t clock_hz, std::uint32_t baud) {
    if (baud == 0) invalid_uart_setting();
    return static_cast<std::uint32_t>(
        (static_cast<std::uint64_t>(clock_hz) + baud / 2) / baud);   // rounded to nearest
}

// true when |clock / divisor - baud| <= baud * permille / 1000, in exact integers.
// Supported inputs: divisor 1..65535 (a 16-bit register), baud > 0, permille <= 1000.
// Then divisor * baud < 2^48 and every product below stays under 2^58, far inside 64 bits.
constexpr bool baud_error_within(std::uint32_t clock_hz, std::uint32_t baud,
                                 std::uint32_t divisor, std::uint32_t permille) {
    if (baud == 0 || divisor == 0 || divisor > 0xFFFF || permille > 1000)
        invalid_uart_setting();
    std::uint64_t ideal = static_cast<std::uint64_t>(divisor) * baud;
    std::uint64_t diff  = clock_hz > ideal ? clock_hz - ideal : ideal - clock_hz;
    return diff * 1000 <= ideal * permille;
}

constexpr std::uint32_t baud    = 115'200;
constexpr std::uint32_t divisor = uart_divisor(sysclk_hz, baud);

static_assert(divisor >= 1 && divisor <= 0xFFFF, "divisor does not fit the 16-bit register");
static_assert(baud_error_within(sysclk_hz, baud, divisor, 20), "baud error above 2%");

Zero is rejected explicitly. A baud rate of 0, a divisor of 0, a divisor wider than the 16-bit register or a tolerance above 100% reaches invalid_uart_setting(), which is not constexpr, so the build fails with an error that names it instead of a division by zero or a silent wrap.

Within those bounds the comparison is exact. Instead of working out an actual rate and truncating a percentage, it multiplies both sides of |clock/divisor − baud| ≤ 2% × baud by the divisor and compares whole numbers in 64 bits. With a divisor of at most 65535 and a 32-bit baud rate, no product comes near the 64-bit limit, so nothing rounds or overflows, and a rate just above 2% is rejected. At 16 MHz the divisor is 139, giving 115,107.9 baud, an error of 0.08%. At a 1 MHz clock the best divisor is 9, about 3.5% off, and the assertion fails the build.

The ±2% budget is a common rule of thumb for UART links. Check your own peripheral: some UARTs use oversampling or fractional dividers, and the formula changes with them.

consteval and constinit (C++20)

constexpr allows compile-time evaluation but does not force it. consteval does: every call must be evaluated by the compiler, or the build fails. That suits values that should never be computed at runtime, such as pin masks:

#include <cstdint>

void pin_out_of_range();   // deliberately not constexpr

consteval std::uint32_t pin_mask(unsigned pin) {
    if (pin > 15) pin_out_of_range();   // a compile error if ever reached
    return 1u << pin;
}

constexpr auto led_mask = pin_mask(5);   // 0x20
static_assert(led_mask == 0x20);
// constexpr auto bad = pin_mask(20);    // does not compile

This avoids throw, which many embedded builds disable with -fno-exceptions.

constinit solves a different problem. It guarantees that a global or static variable is initialised statically, before any constructor runs, but leaves it writable. That removes the static initialisation order surprise for variables that an interrupt handler or early startup code may touch:

#include <cstdint>

constinit std::uint32_t tick_count = 0;   // initialised before any constructor runs

If the initialiser is not a constant expression, the build fails instead of quietly creating a runtime constructor. constinit is only about initialisation: a variable shared with an interrupt handler still needs std::atomic, a critical section or your platform’s equivalent.

Where the table actually goes: evidence from three toolchains

Compile-time evaluation and storage are two separate questions. constexpr decides when the values are computed. Storage duration, the optimiser and the linker decide where the object lives. To show the difference, the same 256-byte CRC table was compiled three ways: at namespace scope, as a local constexpr array inside a function, and as a local static constexpr array. To keep the test free of library differences, it uses a plain struct around a C array instead of std::array. This is the complete source:

// sections.cpp: the same 256-byte table, stored three ways
#include <stdint.h>

struct Table { uint8_t v[256]; };

constexpr Table make_crc8_table(uint8_t poly) {
    Table t{};
    for (int i = 0; i < 256; ++i) {
        uint8_t crc = static_cast<uint8_t>(i);
        for (int bit = 0; bit < 8; ++bit)
            crc = (crc & 0x80) ? static_cast<uint8_t>((crc << 1) ^ poly)
                               : static_cast<uint8_t>(crc << 1);
        t.v[i] = crc;
    }
    return t;
}

constexpr Table ns_table = make_crc8_table(0x07);       // namespace scope

uint8_t read_ns(uint8_t i) { return ns_table.v[i]; }

uint8_t read_local(uint8_t i) {
    constexpr Table t = make_crc8_table(0x07);          // local constexpr
    return t.v[i];
}

uint8_t read_static(uint8_t i) {
    static constexpr Table t = make_crc8_table(0x07);   // local static constexpr
    return t.v[i];
}

And these are the commands that produce the assembler output:

arm-none-eabi-g++     -std=c++20 -O2 -mcpu=cortex-m4 -mthumb -S sections.cpp -o arm.s
xtensa-esp32-elf-g++  -std=c++20 -O2 -S sections.cpp -o esp32.s
avr-g++               -std=c++20 -O2 -mmcu=atmega328p -S sections.cpp -o avr.s

Here is read_local() from the ARM output (GCC 11.2.1, Cortex-M4):

read_local(unsigned char):
        push    {r4, lr}
        sub     sp, sp, #256      @ room for the whole table on the stack
        mov     r4, r0
        ldr     r1, .L7           @ source: the table's image in .rodata
        mov     r2, #256
        mov     r0, sp
        bl      memcpy            @ copied on every call
        ldrb    r0, [sp, r4]
        add     sp, sp, #256
        pop     {r4, pc}

What the three toolchains produced:

Namespace scope. On all three, the table is emitted once as a 256-byte object in the .rodata section. No code builds it, and read_ns() is a single indexed load.

Local constexpr, without static. The values are still computed by the compiler; nothing is recalculated. But the object has automatic storage, and in these builds, where the code indexes it with a runtime value, all three compilers gave it a copy on the stack: ARM reserves 256 bytes and calls memcpy (above), ESP32 opens a 288-byte frame (entry sp, 288) and calls memcpy, and AVR reports 258 bytes of stack usage and copies the bytes in with a loop. The C++ standard does not require this. It describes an object with automatic storage, not where it must live, and a compiler is free to read the original in place when it can prove nobody can tell the difference. These compilers, at -O2, did not, so it is not something to rely on. With a constant index, the optimiser usually folds the value away and no copy remains.

Local static constexpr. One object with static storage in .rodata, read in place exactly like the namespace-scope table. No stack frame, no copy.

So for tables inside functions, write static constexpr. That gives the object static storage by the language’s rules, rather than leaving it to the optimiser.

This is compiler output, not linked firmware. Where .rodata finally ends up is the linker script’s decision, and that placement was not tested on physical boards. Here the chips differ:

STM32 (Cortex-M). The usual GCC linker scripts from ST and CMSIS place .rodata in flash. In the map file, the table sits in the flash region next to .text.

ESP32. ESP-IDF maps .rodata to flash, read through the cache. Code that runs while the cache is disabled, such as an IRAM interrupt handler, cannot read it. Mark tables used there with DRAM_ATTR, which puts them in RAM.

AVR. Flash and RAM are separate address spaces, and avr-gcc’s default linker scripts put .rodata into the .data output section. At startup, __do_copy_data copies it from flash into RAM. On AVR, then, a constexpr table costs RAM unless you add PROGMEM and read it with pgm_read_byte() (or use the __flash qualifier in C). The Arduino AVR core also lacks the C++ standard library, so std::array may be missing; a struct around a C array, as in the test above, does the same job.

Check it in your own build. Toolchain versions and linker scripts vary, so confirm it in your project:

Add -Wl,-Map=firmware.map to the link flags and search the map for the table’s name. You want it in a flash region (.rodata or .text on Cortex-M, .progmem on AVR), not in .data.

arm-none-eabi-nm -C -S –size-sort firmware.elf lists each symbol’s size and type (R/r for read-only data, D/d for data in RAM). avr-nm works the same way.

arm-none-eabi-size or avr-size before and after the change shows the bytes moving between .data and .text. In ESP-IDF, idf.py size-components does the same.

Wrapping up

constexpr moves the arithmetic to the compiler. static_assert turns that arithmetic into tests that run on every build, and consteval and constinit close the gaps constexpr leaves open. Whether the result also saves RAM depends on storage duration and the linker script, so make tables static, add PROGMEM on AVR, and check the map file. Start with one lookup table in your current project and you will see exactly where the bytes went.

Leave a Reply