In C++, what puts a lookup table in read-only memory, and which declarations silently move it to RAM or rebuild it at start-up?
answer
- constant initialization, not just const
- constexpr implies const
- constinit keeps it writable
- a dynamic initializer runs at start-up
- a non-static local is copied
basics
~20 sA constexpr table at namespace scope, or a static constexpr local, is constant-initialized and const, so toolchains put it in a read-only section kept in flash. constinit tables stay in RAM; const tables with runtime initializers are built at start-up.
solid answer
~50 sTwo properties decide it: the object must be **constant-initialized** (its value is fixed at compile time) and **const** (nobody may write it). `constexpr` on a variable gives both, because it requires a constant expression and makes the object const, so a namespace-scope `constexpr std::array` or a `static constexpr` local is the reliable form. Section placement is the toolchain's choice, not the standard's: for a Cortex-M target Clang put such a table in `.rodata`, which firmware links into flash. The traps: `constinit` (C++20) guarantees constant initialization but leaves the object mutable, so it lands in `.data`, in RAM; a `const` table whose initializer calls a function at run time is dynamically initialized, so it occupies `.bss` and a start-up constructor fills it; and a non-static `constexpr` local array is an automatic object, which at `-O0` Clang copied onto the stack, 512 bytes, on every call.
code
cpp · 21 linesusing u16 = unsigned short;
consteval u16 crc_entry(unsigned i) {
u16 c = static_cast<u16>(i << 8);
for (int b = 0; b < 8; ++b) c = static_cast<u16>((c & 0x8000) ? (c << 1) ^ 0x1021 : c << 1);
return c;
}
struct Table { u16 v[256]; };
consteval Table make_table() { Table t{}; for (unsigned i = 0; i < 256; ++i) t.v[i] = crc_entry(i); return t; }
constexpr Table rom_table = make_table(); // constant-initialized, const
constinit Table ram_table = make_table(); // constant-initialized, mutable
u16 seed(); // defined elsewhere, runtime value
const u16 dyn_table[4] = {seed(), 1, 2, 3}; // const, but dynamic initialization
u16 lookup_rom(unsigned i) { return rom_table.v[i & 0xff]; }
u16 lookup_ram(unsigned i) { return ram_table.v[i & 0xff]; }
u16 lookup_dyn(unsigned i) { return dyn_table[i & 3]; }
u16 lookup_local(unsigned i) {
constexpr Table local = make_table(); // automatic storage duration
return local.v[i & 0xff];
}go deeper
Know that constexpr tables can stay in flash, while tables built at start-up cost RAM.
Explain constant initialization, why const alone is not enough, and the difference between constexpr and constinit.
Verify placement in the map file, fix tables that are dynamically initialized, and make debug builds safe with static constexpr locals.
Set the project convention for read-only data, including generated tables and how their placement is checked in CI.
## Why it matters on a microcontroller A pacing-firmware image runs from flash and has far less RAM than flash: a few tens of kilobytes of RAM is common. A CRC table, a sine table for waveform generation or a calibration curve can easily be several hundred bytes to a few kilobytes. If such a table is placed in flash it costs no RAM and no start-up time; if it is placed in RAM it costs both, because the start-up code must copy or compute it. The C++ standard says nothing about flash, RAM or sections. What it defines is when an object is initialized and whether it may be modified, and toolchains map those properties to sections. ## The two properties that matter - **Constant initialization.** A variable with static storage duration whose initializer is a constant expression is initialized before any code runs; no constructor executes at start-up. - **Const.** The program may not modify the object, so the toolchain is free to put it in memory that cannot be written. `constexpr` on a variable requires the first and implies the second (the standard says the `constexpr` specifier in an object declaration declares the object as const). Since C++20, `consteval` functions let you compute such a table at compile time with loops, as in the example below. ## What the compiler did, declaration by declaration The same 256-entry `uint16_t` CRC table was declared four ways and compiled with Clang 21 for a Cortex-M target: | Declaration | Initialization | Section chosen | In flash? | |---|---|---|---| | `constexpr Table rom_table = make_table();` at namespace scope | constant | `.rodata` | yes | | `constinit Table ram_table = make_table();` | constant | `.data` | no: RAM, with its initial image copied from flash at start-up | | `const u16 dyn_table[4] = {seed(), 1, 2, 3};` | dynamic, `seed()` runs at start-up | `.bss` plus a constructor in `.init_array` | no | | `constexpr Table local = make_table();` inside a function | automatic object | at `-O2` merged into `.rodata`; at `-O0` copied to the stack on each call | depends on optimisation | Notes on the rows: 1. **`constinit`** (C++20) is useful for mutable globals that must not be dynamically initialized, avoiding the static-initialization-order problem, but it does not make the object const, so it cannot live in flash. 2. **A `const` table is not enough.** `const` alone does not require a constant initializer. One call to a non-`constexpr` function in the initializer turns it into dynamic initialization: RAM is reserved and a start-up constructor writes it. 3. **A non-static local** has automatic storage duration: in principle a fresh object per call. An optimizer may fold it into a read-only constant, but at `-O0` Clang reserved 520 bytes of stack and called `__aeabi_memcpy` on every call, which can overflow a small stack in a debug build. Write `static constexpr` for a local table. ## Checking it in your own build Because placement is a toolchain decision, verify it rather than assume it: - Read the linker map file or run a size tool on the image: the table should appear in the read-only section. - Add `static_assert` checks on values you rely on, such as `rom_table.v[1] == 0x1021`, so a change to the generator is caught at compile time. - Keep table element types trivial: `std::array` of integers or of simple aggregates. A `constexpr` `std::string` compiles only if the text fits the library's small-string buffer, an implementation detail: with Apple clang 21's libc++ a short string worked and a 50-character one was rejected with `heap allocation performed here`. Use `std::string_view`, whose characters are string literals in read-only storage. ## Generating the table at compile time Writing a 256-entry table by hand invites typos, and generating it with an external script adds a build step. A `consteval` generator (C++20), as in the example, keeps the algorithm in C++: - The values are computed by the compiler, so the table cannot drift from the algorithm. - A mistake that makes the generator not a constant expression, such as reading a global or allocating memory that outlives the evaluation, is a compile error. - `static_assert` can check known entries against a reference, such as `rom_table.v[1] == 0x1021` for this CRC. - Compile time grows with table size; very large tables are still better produced by a generator script or `#embed` in C++26. ## Common mistakes - Marking a table `const` and assuming it is in flash. - Building a table in a constructor of a global object "for clarity", which costs RAM and start-up time. - Using `constinit` where `constexpr` was meant. - Passing the table by value to a helper, which copies it to the stack.
- What is the difference between constexpr and constinit on a C++ global table?Both require constant initialization, so no start-up code runs. `constexpr` also makes the object const, which lets the toolchain place it in read-only memory such as flash. `constinit` (C++20) leaves it mutable, so it must live in writable RAM, typically `.data`, with its initial values copied from flash at start-up.
- Why is a constexpr table of std::string fragile in C++20?C++20 allows allocation during constant evaluation only if it is freed before the evaluation ends. A string that fits the library's small-string buffer needs no allocation and can be `constexpr`; a longer one would keep heap storage alive into run time and is rejected. The buffer size is the library's choice, so use `std::string_view` instead.
- A const global table is always placed in flash.
- constinit makes a table read-only.
- The C++ standard defines which section a constexpr table goes in.
- A constexpr local array is never copied to the stack.
- A table built by a global constructor costs no RAM.