Module 6 · Lesson 4 of 24

Modern C++ for embedded Linux

Rewrite a C HAL in C++20: RAII handles, smart pointers, expected, concepts, jthread and pmr, plus the size flags, sanitizers and tests that ship it.

  • Beginner to advanced
  • 34 min read
  • 55 min lab
What you will need

Ubuntu 24.04 (WSL2, VM or container) with g++ 13 or newer and libgpiod-dev; a Raspberry Pi or QEMU aarch64 target for the size, sanitizer and memory sections

By the end you can 7 objectives
  • Wrap file descriptors, GPIO requests, sockets and database handles in RAII classes that release on every exit path
  • Choose unique_ptr, shared_ptr or weak_ptr for each ownership relationship and justify its cost
  • Model sensor readings and events with optional, variant, span, chrono and filesystem
  • Compare exceptions, std::expected and error codes, and write the -fno-exceptions variant of a service
  • Implement one HAL with std::function, virtual inheritance and concepts, and evaluate the dispatch cost of each
  • Build a producer-consumer pipeline with jthread, condition_variable and atomics that shuts down cleanly
  • Measure binary size and resident memory, run sanitizers and unit tests, and cross-build C++20 for the target
Read the lesson below; the video will appear here when published.
01

Why modern C++ at the application layer

2 min read

The previous lesson built a hardware abstraction layer in C: a struct of function pointers, a real backend over libgpiod, and a mock for tests. It ended with a promise: cleanup on every exit path is exactly what C++ gives you for free when you tie a resource to an object's lifetime. You will now rebuild that HAL in modern C++, then measure what the rewrite costs in binary size, memory and speed on a real target.

"Modern" has a precise meaning here. The 2011 standard, C++11, was the turning point that made ownership automatic and threads standard. C++14 and C++17 added vocabulary types for values that may be missing and events of several kinds. C++20 added compile-time interface checks and threads that clean up after themselves. C++23 added a standard way to return either a value or an error. Ubuntu 24.04 ships g++ 13, which supports all of them with -std=c++20 or -std=c++23. The M8 module taught you the language mechanics; this lesson is about using them where resources are counted in kilobytes and the program must run for years without a reboot.

The guiding rule is the . A class with a constructor and destructor compiles to the same open and close calls you would write in C. You pay only for the features you actually reach for, and this lesson shows the price tag of each.

C++ is already the default language of embedded stacks you will meet later: Qt for device interfaces, ROS 2 for robotics, and AUTOSAR Adaptive in vehicles. Keeping it small and deterministic is a product skill. The running example stays the button-and-LED HAL from the previous lesson.

Where C++ sits in an embedded applicationProduct logicpipelines, services, UIC++20 HAL and typesRAII handles, expected, conceptsC librarieslibgpiod, sqlite3, libcKernelsyscalls and device nodesHardwareGPIO, I2C, SPIC++ compiles down to the same C callsProduct logicpipelines, services, UIC++20 HAL and typesRAII handles, expected,conceptsC librarieslibgpiod, sqlite3, libcKernelsyscalls and device nodesHardwareGPIO, I2C, SPIC++ compiles down to the same Ccalls
Where C++ sits in an embedded application: above the C libraries, below the product logic
02

RAII for hardware handles

3 min read

is the core idea here. In C you close a descriptor on every return path, and one early return leaks it. In C++ the destructor runs on normal exit, on early return, and when an exception unwinds the stack. The leak becomes impossible by construction.

Start with the simplest handle, a file descriptor. The same class wraps a socket, an I2C bus node, an evdev node or a serial port, because they are all descriptors:

cpp
#include <unistd.h>
#include <utility>

class Fd {
public:
    explicit Fd(int fd = -1) noexcept : fd_(fd) {}
    ~Fd() { if (fd_ >= 0) ::close(fd_); }
    Fd(const Fd&) = delete;
    Fd& operator=(const Fd&) = delete;
    Fd(Fd&& other) noexcept : fd_(std::exchange(other.fd_, -1)) {}
    Fd& operator=(Fd&& other) noexcept {
        if (this != &other) {
            if (fd_ >= 0) ::close(fd_);
            fd_ = std::exchange(other.fd_, -1);
        }
        return *this;
    }
    int get() const noexcept { return fd_; }
    int release() noexcept { return std::exchange(fd_, -1); }
private:
    int fd_;
};

Copying is deleted because two objects closing the same descriptor is a double free. Moving transfers ownership and empties the source, so exactly one destructor ever closes it. release() hands the raw descriptor back to C code that insists on owning it. Opening a bus becomes one line, and every later error path is clean:

cpp
#include <fcntl.h>

bool probe_bus() {
    Fd bus(::open("/dev/i2c-1", O_RDWR));
    if (bus.get() < 0) return false;   // nothing to clean up
    return true;                       // bus closes here, automatically
}

GPIO needs two handles: the chip and the requested line. Using the libgpiod 1.x API from the previous lesson, the chip fits an owning pointer of the kind the next section introduces, and the line request fits a small class:

cpp
#include <gpiod.h>
#include <stdexcept>

class GpioLine {
public:
    GpioLine(gpiod_chip* chip, unsigned offset, bool output)
        : line_(gpiod_chip_get_line(chip, offset)) {
        if (!line_) throw std::runtime_error("no such line");
        int rc = output
            ? gpiod_line_request_output(line_, "cpp-hal", 0)
            : gpiod_line_request_input(line_, "cpp-hal");
        if (rc < 0) { line_ = nullptr; throw std::runtime_error("request failed"); }
    }
    ~GpioLine() { if (line_) gpiod_line_release(line_); }
    GpioLine(const GpioLine&) = delete;
    GpioLine& operator=(const GpioLine&) = delete;
    void set(int v) { gpiod_line_set_value(line_, v); }
    int get() { return gpiod_line_get_value(line_); }
private:
    gpiod_line* line_ = nullptr;
};

If the constructor throws, the object never existed, so its destructor never runs; the failed request sets line_ to null instead of releasing a line it never claimed. The chip handle owns the line objects, so declare it first: destruction runs in reverse order.

Step by stepA GPIO request from construction to release
  1. Construct: the constructor gets the line and requests it with a consumer name

  2. Check: a failed request throws, and no object exists to clean up

  3. Use: set and get go through the member functions, never the raw pointer

  4. Scope ends: a return, a break or an exception all start destruction

  5. Release: the destructor calls gpiod_line_release, returning the line to the kernel

  6. Chip closes: the owning chip handle is destroyed last, after every line

Going deeperWhat a destructor must never do

A destructor runs during stack unwinding when an exception is already in flight. If it throws a second exception, the runtime calls std::terminate. Destructors are therefore implicitly noexcept, and yours must keep that promise. On Linux, close() always releases the descriptor even when it returns EINTR, so retrying it is a bug: the number may already belong to another thread's new file. The correct destructor ignores the return value or logs it, and never retries. If cleanup can fail in a way the caller must handle, expose an explicit close() that returns an error, and let the destructor be the last-resort net.

A handle object acquires at construction and releases at scope exitScopeHandle objectKernelconstructopen / requesthandleuse: read, write,setsyscallsscope exit orexceptiondestructor: close /release1. Scope → Handle objectconstruct2. Handle object → Kernelopen / request3. Kernel → Handle objecthandle4. Scope → Handle objectuse: read, write, set5. Handle object → Kernelsyscalls6. Scope → Handle objectscope exit or exception7. Handle object → Kerneldestructor: close / release
One handle object acquires at construction and releases at scope exit, even on the error path
03

Smart pointers and ownership

3 min read

A makes ownership visible in the code. The rule for embedded C++ is simple: no raw new and delete in application code. Every heap object is created with std::make_unique or std::make_shared, and every C handle is wrapped in a unique_ptr with a custom deleter.

std::unique_ptr<T> is sole ownership. It cannot be copied, only moved, and with a stateless deleter it is exactly the size of a raw pointer and compiles to the same load and store. That makes it the default for C resources whose release function is not delete:

cpp
#include <gpiod.h>
#include <memory>

struct ChipDeleter {
    void operator()(gpiod_chip* c) const noexcept { gpiod_chip_close(c); }
};
using ChipPtr = std::unique_ptr<gpiod_chip, ChipDeleter>;

void blink() {
    ChipPtr chip(gpiod_chip_open("/dev/gpiochip0"));
    if (!chip) return;                  // error path: nothing to clean up
    GpioLine led(chip.get(), 4, true);  // line released before chip closes
    led.set(1);
}   // led released, then chip closed, automatically

The same pattern wraps a database handle. SQLite's sqlite3_close_v2 is the right deleter because it tolerates unfinalized statements, deferring their cleanup instead of returning SQLITE_BUSY:

cpp
#include <sqlite3.h>
#include <memory>
#include <stdexcept>
#include <string>

using DbPtr = std::unique_ptr<sqlite3, int(*)(sqlite3*)>;

DbPtr open_db(const char* path) {
    sqlite3* raw = nullptr;
    if (sqlite3_open(path, &raw) != SQLITE_OK) {
        std::string msg = raw ? sqlite3_errmsg(raw) : "out of memory";
        sqlite3_close_v2(raw);
        throw std::runtime_error(msg);
    }
    return DbPtr(raw, &sqlite3_close_v2);
}

std::shared_ptr<T> is shared ownership. A control block beside the object holds two atomic counters, strong and weak. Copies and destructions adjust the strong count atomically, and the last owner deletes the object. That atomic traffic is the price: a locked instruction and a cache line shared between cores. Use shared_ptr only where ownership is genuinely shared, such as a logger several services write to. std::make_shared allocates object and control block together, saving one allocation.

std::weak_ptr<T> observes without owning. lock() returns a shared_ptr if the object is still alive, or an empty one if it is gone. Its main job is breaking cycles: two objects that hold shared_ptr to each other never reach zero, and both leak. Make one direction weak.

is what makes unique_ptr practical: returning handles from factories, storing them in containers, handing them to threads. A raw pointer parameter should mean "I observe this, I do not own it"; keep that convention.

A shared_ptr cycle is a leak the compiler cannot see

An observer list where the subject owns the observers and each observer owns the subject back never frees anything. Valgrind and ASan report it only at exit, if at all. Draw the ownership graph before you write it: arrows are shared_ptr, dashed arrows are weak_ptr, and there must be no cycle of solid arrows.

unique_ptr, shared_ptr and weak_ptrunique_ptrshared_ptrweak_ptrOwnersexactly onemany, countednone,observesCopyingmove onlycopy bumpscountcopy, thenlock()Run-time costzero overheadatomicrefcountsatomic checkon lockUse forC handles,sole ownersharedservicesbreakingcycles
unique_ptr, shared_ptr and weak_ptr compared on ownership, cost and copying
04

Core library types for a sensor pipeline

3 min read

The C HAL returned ints and used sentinel values: -1 for error, 0xFF for a dead sensor. The standard library has types that say exactly what a value means, and they compile to the same machine code as the sentinels when optimized.

std::optional<T> (C++17) holds a value or nothing. A sensor read that can fail returns std::optional<Reading>; the caller must check before using it. std::variant<A, B> (C++17) holds exactly one of several types, a type-safe union. Events in a pipeline are a variant of reading and button press; std::visit dispatches on the active type with no manual tag field.

cpp
#include <chrono>
#include <format>
#include <optional>
#include <string>
#include <type_traits>
#include <variant>

struct Reading { double celsius; std::chrono::steady_clock::time_point at; };
struct ButtonEvent { bool pressed; };
using Event = std::variant<Reading, ButtonEvent>;

std::optional<Reading> read_temperature(Fd& bus);   // empty on bus error

std::string describe(const Event& e) {
    return std::visit([](const auto& ev) -> std::string {
        if constexpr (std::is_same_v<std::decay_t<decltype(ev)>, Reading>)
            return std::format("{:.1f} C", ev.celsius);
        else
            return ev.pressed ? "button down" : "button up";
    }, e);
}

std::span<T> (C++20) is a non-owning view of a contiguous sequence: a pointer and a length. Pass std::span<const std::byte> to a frame parser instead of a pointer plus a size argument, and the length travels with the pointer, so the parser cannot read past the end by miscounting. It copies nothing, and because it does not own the buffer, the buffer must outlive the span.

std::chrono (C++11) makes time a type. Durations carry their unit, so milliseconds cannot be confused with seconds. Use steady_clock for intervals and timeouts, because it never jumps when the system clock is set; use system_clock only for wall-clock timestamps. On a board without a battery-backed clock, the wall clock can jump at boot when NTP syncs, and a timeout built on it misbehaves.

std::string, std::vector and std::map are the workhorses you met in M8. Two embedded habits matter. First, reserve() vectors at startup so the hot path never reallocates. Second, libstdc++'s string keeps up to 15 characters inside the object itself (the small-string optimization), so short names and keys allocate nothing. std::filesystem (C++17) replaces hand-rolled path strings: path, exists(), file_size() and rename() handle separators and errors, and rename() within one filesystem is atomic.

Library types carrying a sample through the pipelineRead sensoroptional<Reading>value ornothingvariant<Event>reading orbuttonspan viewparsewithoutcopyingchronostampsteady_clock timeRead sensoroptional<Reading>value ornothingvariant<Event>reading orbuttonspan viewparsewithoutcopyingchronostampsteady_clock time
How optional, variant, span and chrono carry a sample through the pipeline
05

Error handling: exceptions, expected, and -fno-exceptions

4 min read

C++ gives you three error channels. Knowing their costs lets you follow whichever rule your product imposes.

Exceptions separate the happy path from error handling. A constructor that cannot acquire its resource throws, and RAII cleans up every object built so far. The Itanium C++ ABI used on Linux makes this table-driven: the happy path executes no extra instructions, and the cost lives in unwind tables that grow the binary. A thrown exception is expensive, because unwinding walks those tables and runs every destructor. Many embedded style guides, including Google's, ban exceptions outright, because the worst-case path is hard to bound.

Result types return the error in the value. is std::expected<T, E> in C++23, available in libstdc++ since GCC 12. It is the modern form of the old "return an error code" discipline, but the success value travels with it and the type system enforces the check:

cpp
#include <expected>
#include <charconv>
#include <string_view>

enum class ParseError { empty, not_a_number, out_of_range };

std::expected<int, ParseError> parse_percent(std::string_view s) {
    if (s.empty()) return std::unexpected(ParseError::empty);
    int value = 0;
    auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value);
    if (ec != std::errc{} || ptr != s.data() + s.size())
        return std::unexpected(ParseError::not_a_number);
    if (value < 0 || value > 100)
        return std::unexpected(ParseError::out_of_range);
    return value;
}

The caller writes if (auto r = parse_percent(input); r.has_value()) use(*r); else report(r.error());. On C++17 toolchains, the header-only tl::expected library provides the same interface, and Boost.Outcome offers a richer variant with hooks for logging and assertions. Pick one and use it consistently.

Error codes are the plain C channel: an int or enum return, with the value passed through an out-parameter. They work everywhere, including the smallest targets, but nothing forces the caller to look. If you use them, mark the function [[nodiscard]] so the compiler warns when the result is ignored.

The -fno-exceptions build is the embedded variant of all this. With that flag, GCC rejects throw and catch in your code, and the failure paths inside the standard library, such as vector::at out of range or a failed allocation, call abort() instead of throwing. Your code must therefore use expected or error codes everywhere, and check preconditions before calling library functions that can fail. The reward is smaller code: no unwind tables for your functions, and no exception machinery linked in.

Going deeperWhat -fno-exceptions and -fno-rtti actually remove

With exceptions enabled, every function that can unwind gets a .gcc_except_table entry and frame information in .eh_frame, even if it never throws; that is pure binary size. -fno-exceptions stops generating those tables for your code and lets the linker drop the unwinder. -fno-rtti is a separate switch: it removes the typeinfo objects and name strings that dynamic_cast and typeid need, and shrinks every polymorphic vtable. Neither feature costs run time when unused, but the tables still cost flash. Measure with size(1) before and after; some third-party libraries require RTTI or exceptions, so the flags are a product-wide decision.

Three error channels comparedExceptionsstd::expectedError codesError travels bystackunwindingreturn valuereturn valueHappy-path costzero, tablesin flashone branchone branchCaller mustchecknoyes, by typeno, unlessnodiscard-fno-exceptionsunavailableworksworks
Exceptions, std::expected and error codes compared on cost and enforcement
06

One HAL, three dispatch mechanisms

4 min read

The previous lesson's HAL was a struct of function pointers. C++ offers three ways to express the same idea, trading flexibility against cost. This section builds all three.

Lambdas and std::function. A lambda is an unnamed function object; its captures are the variables it carries along. std::function is a wrapper that can hold any callable with a matching signature. It works by . A struct of std::function members is the direct C++ translation of hal_ops:

cpp
#include <functional>
#include <memory>

struct FnHal {
    std::function<void(int)> set_led;
    std::function<int()> read_button;
};

FnHal make_loopback_mock() {
    auto state = std::make_shared<int>(0);
    return FnHal{
        [state](int on) { *state = on; },
        [state]() { return *state; }
    };
}

This mock reads back whatever was written, which is enough to test sequencing logic. To adapt a member function, capture this in a lambda: [this](int v){ on_button(v); }. Prefer that over std::bind, which is harder to read and easy to get wrong with placeholders.

A capture is a promise about lifetime

[&] captures references, and [this] captures a pointer. If the callback outlives the frame or the object, calling it is undefined behaviour, and it usually crashes far from the bug. For callbacks that cross threads or outlive the call, capture by value, or capture a shared_ptr with an init-capture: [p = std::move(ptr)].

Virtual inheritance. An abstract base class with pure virtual functions is the classic HAL: struct Hal { virtual void set_led(int) = 0; virtual int read_button() = 0; virtual ~Hal() = default; };. Backends derive from it, and a factory returns std::unique_ptr<Hal>. The cost is one vtable lookup and an indirect branch per call, with no inlining across it. The benefit: one binary can load any backend at run time, which a multi-board product needs.

Templates and concepts. A lets you write the interface as a constraint and let the compiler resolve everything:

cpp
#include <concepts>

template <typename T>
concept GpioBackend = requires(T t, int v) {
    { t.set_led(v) } -> std::same_as<void>;
    { t.read_button() } -> std::same_as<int>;
};

template <GpioBackend B>
void run_product(B& hal) {
    hal.set_led(hal.read_button());
}

run_product(real_hal) and run_product(mock_hal) instantiate two copies of the logic, each with direct, inlinable calls and zero indirection. That is the zero-overhead principle applied to the HAL. The price is code size when many backends exist, and the backend must be known at compile time. A factory that forwards its arguments perfectly keeps the construction generic:

cpp
template <typename Backend, typename... Args>
std::unique_ptr<Hal> make_hal(Args&&... args) {
    return std::make_unique<Backend>(std::forward<Args>(args)...);
}

Args&&... is a pack of forwarding references, and std::forward preserves whether each argument was an lvalue or an rvalue, so move-only handles arrive without copies.

Compile-time work. constexpr functions run at compile time when their inputs are constant, and constinit (C++20) guarantees a static variable is initialized at compile time, removing one form of the static initialization order problem. A Modbus CRC table is a good example: computed once by the compiler, stored in flash, never built at boot:

cpp
#include <array>
#include <cstdint>

constexpr auto make_crc_table() {
    std::array<std::uint16_t, 256> t{};
    for (std::size_t i = 0; i < 256; ++i) {
        std::uint16_t c = static_cast<std::uint16_t>(i);
        for (int k = 0; k < 8; ++k)
            c = (c & 1) ? (c >> 1) ^ 0xA001 : c >> 1;
        t[i] = c;
    }
    return t;
}
constinit const auto crc_table = make_crc_table();
static_assert(crc_table[1] == 0xC0C1);
Going deeperInside std::function: the small buffer and the manager

libstdc++'s std::function stores two function pointers, an invoker and a manager, plus a small local buffer. A capture that fits in the buffer (16 bytes on 64-bit), is suitably aligned and is nothrow-move-constructible is stored inline; anything larger is heap-allocated, and the manager knows how to copy, move or destroy it. Every call goes through the invoker, an indirect branch the compiler cannot inline. A lambda with two int captures is allocation-free; one capturing a std::string and a vector may allocate on construction. In a hot path, that hidden allocation is exactly what you must design out.

One HAL, three dispatch mechanismsstd::functionVirtual baseTemplate +conceptResolved atrun timerun timecompile timeInliningnonoyesPer-call costindirect,maybe heapvtable lookupzeroSwap at run timeyesyesno, rebuild
The same HAL dispatched through std::function, a virtual base, or a concept-constrained template
07

Concurrency for sensor pipelines

4 min read

A sensor service is usually a pipeline: one thread reads hardware, another processes and publishes. C++20 gives you the tools to build it and, just as important, to shut it down without a crash.

std::thread starts a thread, but its destructor calls std::terminate if the thread is still joinable, meaning neither joined nor detached. Forgetting to join is a classic crash at exit. std::jthread (C++20) fixes this: its destructor requests stop and then joins. The request travels through a , so shutdown is cooperative, never a forced kill.

cpp
#include <thread>
#include <stop_token>
#include <mutex>
#include <condition_variable>
#include <queue>

std::queue<Event> q;
std::mutex m;
std::condition_variable_any cv;
void process(const Event& e);   // the pipeline stage, defined elsewhere

void consumer(std::stop_token stop) {
    std::unique_lock lock(m);
    while (!stop.stop_requested()) {
        cv.wait(lock, stop, [] { return !q.empty(); });
        if (stop.stop_requested()) break;
        Event e = std::move(q.front());
        q.pop();
        lock.unlock();
        process(e);
        lock.lock();
    }
}

// in main: the producer pushes under the mutex and calls cv.notify_one()
std::jthread worker(consumer);   // destructor requests stop and joins

Three details carry the correctness. The wait takes a predicate, because condition variables can wake spuriously; the loop re-checks the queue. The stop_token overload of wait (on condition_variable_any) also wakes when stop is requested, so a blocked worker cannot hang shutdown. The mutex is unlocked while processing, so the producer never waits on slow work.

std::atomic<T> shares a single value without a mutex. Use it for counters and flags: std::atomic<bool> running or a sample counter with memory_order_relaxed, which is enough for statistics. Publishing data through a flag needs acquire/release ordering; the M8 concurrency session covers the memory model in depth. For one-shot results, std::async(std::launch::async, fn) returns a std::future, and std::promise lets a thread set a value by hand. One trap: the future returned by std::async blocks in its destructor until the task finishes, so discarding it is not fire-and-forget.

On embedded targets, threads have a price beyond CPU. Each thread gets a stack, 8 MiB of virtual address space by default on Linux; std::thread exposes no stack-size knob, so a many-thread service on a small 32-bit address space may need pthread_attr_setstacksize directly. For a control loop that must meet deadlines, pthread_setschedparam on native_handle() can raise the thread to SCHED_FIFO, which needs privilege, and pairs with the PREEMPT_RT kernel of the real-time module. Beware priority inversion: a high-priority thread waiting on a mutex held by a low-priority one inherits its latency.

Step by stepClean shutdown of a jthread worker
  1. Request: the owner calls request_stop, or the jthread destructor does it

  2. Wake: the stop token wakes any condition_variable_any wait

  3. Notice: the worker sees stop_requested and leaves its loop

  4. Drain: the worker finishes or discards queued work by design, not by accident

  5. Join: the destructor joins, so main proceeds only after the worker is gone

Clean shutdown of a jthread workerMainWorkerCond varjthread startsworkerwait(lock, token,pred)request_stop()stop wakes the waitworker exits loopdestructor joins1. Main → Workerjthread starts worker2. Worker → Cond varwait(lock, token, pred)3. Main → Workerrequest_stop()4. Worker → Cond varstop wakes the wait5. Worker → Mainworker exits loop6. Main → Workerdestructor joins
A jthread worker waiting on a condition variable, woken by a stop request, then joined
08

C and C++ interop, ABI, and the cross toolchain

3 min read

Your C++ service calls C libraries: libgpiod, sqlite3, libc itself. The bridge is . A C++ function void set_led(int) becomes a symbol like _Z7set_ledi, while the C library exports plain set_led. extern "C" tells the compiler to use the C name and linkage:

cpp
extern "C" {
#include "legacy_driver.h"   // a C header without its own guards
}

Well-maintained C headers, including gpiod.h, already wrap themselves in #ifdef __cplusplus guards, so you include them normally. Two rules keep the border safe. An extern "C" function cannot be overloaded, because there is only one name. And never let an exception escape through a C callback: C objects are usually built without unwind information, so the throw cannot find its way out and the process terminates. Catch everything at the boundary and convert it to an error code.

The is why the toolchain must match the target. On ARM, the triplet aarch64-linux-gnu names 64-bit ARM with glibc; arm-linux-gnueabihf names 32-bit ARM with hardware floating point, as the Molloy cross-compilation chapter explains. Mixing hard-float and soft-float objects fails at link time or, worse, passes garbage in floating-point registers.

C++ adds one more ABI layer: the standard library. GCC links libstdc++ by default; Clang can use libc++ with -stdlib=libc++. They are different implementations with different ABIs, and the target must carry whichever you linked, at a version new enough for your symbols. A C++20 binary built against a recent libstdc++ will not start on an older image: the dynamic linker reports a missing GLIBCXX_3.4.xx version. Check before shipping:

bash
readelf -V ./sensor-service | grep GLIBCXX      # versions the binary needs
strings /usr/lib/aarch64-linux-gnu/libstdc++.so.6 | grep GLIBCXX   # what the target has
The target's libstdc++ is part of your build

The clean fix is the one from the CMake lesson: build with the same SDK that built the image, so compiler and library match by construction. If you must use a newer compiler, ship the matching libstdc++.so.6 with the application, or fall back to C++17 plus tl::expected on targets whose library is older. Never copy a host libstdc++ onto the board.

One more ABI trap lives inside libstdc++: since GCC 5 it has two ABIs for std::string and std::list, selected by _GLIBCXX_USE_CXX11_ABI. Objects built with different settings fail to link with errors mentioning std::__cxx11. Keep the setting uniform across your project and every prebuilt library.

For shared libraries you build, -fvisibility=hidden hides every symbol by default; mark the public API with a visibility attribute or a version script. The dynamic symbol table shrinks and loading gets faster. And remember that extern "C" gives you C linkage, not C semantics: both sides still must agree on struct layout, ownership and who frees what.

The runtime layers a C++ binary depends onYour C++20 codeHAL, pipeline, serviceslibstdc++ or libc++must match at run timelibcglibc or muslKernelsyscalls, dynamic loadership the library you linked againstYour C++20 codeHAL, pipeline, serviceslibstdc++ or libc++must match at run timelibcglibc or muslKernelsyscalls, dynamic loadership the library you linkedagainst
The runtime layers a C++ binary depends on, from your code down to the kernel
09

Memory on a constrained target

4 min read

A service that runs for years cannot treat the heap casually. Two failure modes dominate. A leak grows resident memory until the OOM killer acts. Fragmentation is subtler: freed blocks leave holes too small for the next request, so the allocator keeps asking the kernel for more pages even though total free bytes look sufficient. Long-running daemons with churny allocation patterns drift upward for weeks and then die.

The first defense is design: allocate at startup, then never again in the hot path. reserve() every vector, size every buffer for the worst case, and prefer std::array and fixed buffers where the size is known. When you must allocate dynamically, C++17's polymorphic memory resources give you control. A sits behind every std::pmr container:

cpp
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory_resource>
#include <span>
#include <vector>

void process_frame(std::span<const std::byte> frame) {
    std::array<std::byte, 4096> buf;
    std::pmr::monotonic_buffer_resource pool(buf.data(), buf.size());
    std::pmr::vector<std::uint16_t> samples(&pool);
    samples.reserve(frame.size() / 2);
    // parse into samples: every allocation is a pointer bump
}   // pool releases everything at once; no per-element free

The monotonic resource never frees individual blocks; it bumps a pointer and releases the whole arena at destruction. That is deterministic, fragmentation-free, and fast. When the stack buffer fills, it falls back to an upstream resource, the default heap unless you chain another. For workloads that do free blocks, std::pmr::unsynchronized_pool_resource keeps per-size free lists. is the lower-level tool beneath these pools: new (slot) Sample(args) builds an object in a preallocated slot, and slot->~Sample() ends its life without freeing the storage.

Know what the default allocator does underneath. glibc's malloc serves small requests from the heap and routes large ones, above a 128 KiB threshold by default, to anonymous mmap, which returns to the kernel on free. It also keeps per-thread arenas to reduce lock contention, which can multiply resident memory on a many-thread service; MALLOC_ARENA_MAX caps them. The Simmonds memory chapter covers measurement: VSS counts everything mapped and overstates usage, RSS counts physical pages but double-counts shared libraries, and PSS, from /proc/<pid>/smaps, splits shared pages fairly. Track PSS over days to catch a leak; smemcap on the target plus smem on the host does this without Python on the board.

Measure the right number

A growing VSS is usually harmless address-space reservation. A growing PSS is real memory. Linux also over-commits by default, so a successful malloc is not a promise of physical memory; when the system truly runs out, the OOM killer picks a victim by score, tunable per process with /proc//oom_score_adj.

Going deeperHidden allocations in a hot path, and how to find them

The allocations you did not write are the dangerous ones: a std::function capturing more than the small buffer, a string concatenation past 15 characters, a vector growing past its capacity, a map node per insert. Audit the hot path line by line and ask what allocates. Then prove it: run under Valgrind's massif or heaptrack on the host, or wrap operator new with a counter in a test build. A steady-state service should show zero allocations per cycle; each one you find is a latency spike and a fragmentation opportunity to design out.

A pmr vector on a monotonic stack bufferpmr::vectorneedsmemorymonotonicresourcebump thepointerstackstd::array4096 bytes,no heapExit from step 2: buffer fullupstream heappmr::vectorneedsmemorymonotonicresourcebump thepointerExit from step 2: buffer fullupstream heapstackstd::array4096 bytes,no heap
A pmr vector allocating from a monotonic buffer backed by a stack array, with heap fallback
10

Size, sanitizers, analysis, and tests

3 min read

The lab for this lesson refactors the C HAL into C++ and compares binary size, so you need the flags that make the comparison fair and the tools that keep the rewrite correct.

Size. Build with -Os when flash is the constraint and -O2 when speed is; measure both, because the difference is workload-specific. Add -ffunction-sections -fdata-sections so every function and datum gets its own section, then link with -Wl,--gc-sections so the linker drops the unreferenced ones; this is where unused template instantiations disappear. -fno-exceptions -fno-rtti remove the machinery described earlier, if your error style allows it. -static removes shared-library dependencies but grows the binary and, with glibc, breaks name-service functions like getaddrinfo that dlopen NSS modules at run time; musl-based images static-link cleanly. Use size(1) for section totals and nm --size-sort for the biggest symbols. Strip for shipping, keeping the debug file as the previous lesson showed.

Sanitizers. The sanitizers you met in M0 work on C++ too. AddressSanitizer (-fsanitize=address -fno-omit-frame-pointer -g) catches use-after-free and overflows, exactly what a manual port from C risks; UBSan (-fsanitize=undefined) catches signed overflows and bad casts. Both run on 64-bit ARM targets: cross-compile with the flags and copy the matching libasan from the toolchain to the board, expecting roughly double the run time and a large memory overhead. ThreadSanitizer finds data races but needs a 64-bit target and several times the memory, so run it on the host against the mock HAL instead. Sanitizers are a CI gate, not a production build.

Analysis. Compile with -Wall -Wextra -Wpedantic -Werror and treat every warning as a defect. Run clang-tidy over a compile_commands.json (CMake emits it with CMAKE_EXPORT_COMPILE_COMMANDS=ON) for modernize and bugprone checks, and cppcheck as a second opinion. The C++ Core Guidelines are the reference for what "idiomatic" means here; their rules on ownership and lifetimes are exactly this lesson's themes.

Tests. The virtual HAL from the dispatch section is directly mockable with GoogleMock:

cpp
#include <gmock/gmock.h>
#include <gtest/gtest.h>

struct Hal {
    virtual ~Hal() = default;
    virtual void set_led(int on) = 0;
    virtual int read_button() = 0;
};

class MockHal : public Hal {
public:
    MOCK_METHOD(void, set_led, (int on), (override));
    MOCK_METHOD(int, read_button, (), (override));
};

TEST(Pipeline, LedFollowsButton) {
    MockHal hal;
    EXPECT_CALL(hal, read_button()).WillOnce(::testing::Return(1));
    EXPECT_CALL(hal, set_led(1)).Times(1);
    run_product(hal);
}

Fixtures (TEST_F) share setup across cases, and parameterized tests (TEST_P with INSTANTIATE_TEST_SUITE_P) run the same logic over many inputs, such as every parse_percent error case. For small services, doctest (a single header) and Catch2 (a small library) are lighter alternatives; the choice matters less than having tests. Cross-compile the test binary and run it on the board or under qemu-user, so the mock tests and the hardware-in-the-loop tests from the previous lesson form one pyramid.

The verification pipeline before release-Wall-Wextra-Werrorclang-tidy,cppcheckASan +UBSangtest onmock HAL-Os, --gc-sectionstargetsmoke test-Wall-Wextra-Werrorclang-tidy,cppcheckASan +UBSangtest onmock HAL-Os, --gc-sectionstargetsmoke test
The verification pipeline from warnings to target smoke test
11

Try it

1 min read

Open the lab and refactor the previous session's C HAL into C++20: an Fd class, a GpioLine request wrapper and a ChipPtr, then the same run_product logic against a real backend and a mock. Build it twice, once with exceptions and once with -fno-exceptions and std::expected, and compare the sizes with size(1). Add a jthread consumer with a stop token, run ASan and UBSan on the host and on the target, and write the GoogleTest cases for the mock. The practice pack walks each step and the before-and-after measurements; the answers are yours to produce.

Key takeaways

  • RAII turns every hardware handle into an object whose destructor releases it, on early returns and exceptions alike.
  • unique_ptr with a custom deleter wraps any C handle at zero overhead; shared_ptr adds atomic reference counts, so use it only for real shared ownership.
  • optional, variant and span model missing values, event kinds and buffer views without copies or sentinel values.
  • std::expected (C++23) gives result-style errors that work with -fno-exceptions; tl::expected backports the idea to C++17.
  • std::function buys runtime flexibility with an indirect call and possible heap allocation; concepts and templates resolve the same HAL at compile time for free.
  • jthread plus a stop token shuts a worker down cleanly; a joinable std::thread that is destroyed calls std::terminate.
  • On a constrained target, prefer init-time allocation, pmr monotonic buffers and pools over a churning heap; measure PSS, not VSS.
  • Ship C++ deliberately: -Os with --gc-sections, a matching libstdc++ on the target, sanitizers in CI, and unit tests against the mock HAL.

Reflect

  1. Explain to a colleague, in two sentences: wrap file descriptors, GPIO requests, sockets and database handles in RAII classes that release on every exit path
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?

On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

Practise this lessonExercises, quiz, interview preparation and spaced review

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close