C++ in Embedded Systems: A practical transition from C to modern C++ / C++ во встраиваемых системах: Практический переход с C на современный C++
Год издания: 2025
Автор: Mahmutbegović Amar / Махмутбегович Амар
Издательство: Packt Publishing
ISBN: 978-1-83588-114-9
Язык: Английский
Формат: PDF/EPUB
Качество: Издательский макет или текст (eBook)
Интерактивное оглавление: Да
Количество страниц: 402
Описание: Go beyond C by applying modern C++ in embedded systems to enhance code readability, maintainability, and scalability
Key Features
Bridge the gap between C and modern C++ for embedded systems through practical examples
Learn how to save memory and cut down on runtime computing using compile-time computation techniques
Improve your software design skills by applying patterns to solve common problems in embedded systems using C++
Book Description
Transitioning from C can be daunting, with concerns about performance overhead, added complexity, and unfamiliar tooling. Addressing these challenges, Amar Mahmutbegovic, an advocate for modern C++ in embedded development, shows you how to harness zero-cost abstractions, compile-time checks, and powerful modern C++ capabilities to preserve performance while achieving safer, cleaner code. This book bridges the gap between traditional C and advanced C++, helping you retain the efficiency C developers demand while unlocking the safety and expressiveness of modern C++.
Starting with a modern development environment setup, including a Docker container for seamless example replication, you’ll overcome the hurdles of using the C++ standard library in memory-constrained settings and get acquainted with the Embedded Template Library (ETL) as an alternative. The book walks you through essential C++ concepts before exploring advanced topics such as templates, strong typing, error handling, compile-time computation, and RAII. Through practical examples, you'll implement a sequencer, write a type-safe HAL, and apply patterns like Command, State, and Observer to solve common embedded development problems.
By the end of this book, you’ll have learned how to apply modern C++ to develop robust, modular firmware with performance matching or exceeding hand-coded C solutions.
What you will learn
Debunk myths and misconceptions about using C++ in embedded systems
Set up build automation tailored for C++ in constrained environments
Leverage strong typing to improve type safety
Apply modern C++ techniques, such as Resource Acquisition Is Initialization (RAII)
Use Domain Specific Language (DSL) with a practical example using Boost SML
Implement software development best practices, including the SOLID principle, in embedded development
Who this book is for
This book is for embedded developers who primarily use C and want to adopt a modern C++ approach. It introduces fundamental C++ concepts, making it suitable for beginners, while also assuming basic familiarity to fully leverage advanced features like compile-time computation. Even those with prior C++ experience will discover new ways to apply modern best practices to write more efficient and maintainable embedded applications.
Выходите за рамки C, применяя современный C++ во встраиваемых системах для повышения читаемости, сопровождаемости и масштабируемости кода.
Основные характеристики
Сократите разрыв между C и современным C++ для встраиваемых систем с помощью практических примеров
Узнайте, как экономить память и сокращать время выполнения вычислений, используя методы вычислений во время компиляции
Совершенствуйте свои навыки разработки программного обеспечения, применяя шаблоны для решения распространенных проблем во встраиваемых системах с использованием C++
Описание книги
Переход с языка Си может оказаться непростой задачей, связанной с повышением производительности, дополнительной сложностью и незнакомыми инструментами. Решая эти задачи, Амар Махмутбегович, сторонник современного C++ в области разработки встраиваемых систем, показывает вам, как использовать абстракции с нулевыми затратами, проверки во время компиляции и мощные современные возможности C++ для сохранения производительности при одновременном создании более безопасного и чистого кода. Эта книга устраняет разрыв между традиционным C и продвинутым C++, помогая вам сохранить эффективность, требуемую разработчиками C, одновременно открывая возможности безопасности и выразительности современного C++.
Начав с настройки современной среды разработки, включая контейнер Docker для бесперебойной репликации примеров, вы преодолеете трудности, связанные с использованием стандартной библиотеки C++ в условиях ограниченного объема памяти, и познакомитесь со встроенной библиотекой шаблонов (ETL) в качестве альтернативы. В книге вы познакомитесь с основными понятиями C++, а затем познакомитесь с такими продвинутыми темами, как шаблоны, строгая типизация, обработка ошибок, вычисления во время компиляции и RAII. На практических примерах вы сможете реализовать секвенсор, написать типобезопасный HAL и применить такие шаблоны, как Command, State и Observer, для решения распространенных проблем разработки встраиваемых систем.
К концу этой книги вы узнаете, как применять современный C++ для разработки надежного модульного программного обеспечения, производительность которого соответствует или превосходит производительность решений на C, написанных вручную.
Что вы узнаете
Развенчайте мифы и неправильные представления об использовании C++ во встраиваемых системах
Настройте автоматизацию сборки, адаптированную для C++ в ограниченных средах
Используйте строгую типизацию для повышения безопасности ввода
Применяйте современные методы C++, такие как сбор ресурсов и инициализация (RAII)
Используйте язык, специфичный для предметной области (DSL), на практическом примере используя Boost SML
Применяйте лучшие практики разработки программного обеспечения, включая принцип SOLID, во встроенной разработке
Для кого предназначена эта книга
Эта книга предназначена для разработчиков встраиваемых систем, которые в основном используют C и хотят освоить современный подход к C++. В ней представлены фундаментальные концепции C++, что делает ее подходящей для начинающих, а также предполагается, что базовые знания позволят в полной мере использовать расширенные возможности, такие как вычисления во время компиляции. Даже те, кто уже имеет опыт работы с C++, откроют для себя новые способы применения передовых современных методов для написания более эффективных и удобных в обслуживании встраиваемых приложений.
Примеры страниц (скриншоты)
Оглавление
Preface xvii
Part I: Introduction to C++ in Embedded Development 1
Chapter 1: Debunking Common Myths about C++ 3
Technical requirements ...................................................................................................... 4
A short history of C++ .......................................................................................................... 4
C with Classes ..................................................................................................................... 6
Modern C++ • 6
Generic types • 8
Ring buffer in C • 8
Ring buffer in C++ • 15
constexpr • 17
Bloat and runtime overhead .............................................................................................. 21
Constructors and destructors • 21
Optimization • 26
Templates • 28
RTTI and exceptions • 30
Summary .......................................................................................................................... 33
Join our community on Discord ........................................................................................ 34
Chapter 2: Challenges in Embedded Systems with Limited Resources 35
Technical requirements .................................................................................................... 36
Safety-critical and hard real-time embedded systems ...................................................... 36
Airbag control unit and real-time requirements • 36
Measuring firmware performance and non-determinism • 39
A-B timing and real-time execution • 39
Sotware instrumentation with GCC • 40
Determinism vs. Non-Determinism in Firmware • 41
Dynamic memory management ........................................................................................ 42
Memory fragmentation • 43
Safety-critical guidelines for dynamic memory management in C++ • 44
Dynamic memory management in the C++ standard library • 45
Disabling unwanted C++ features ...................................................................................... 51
Summary .......................................................................................................................... 53
Chapter 3: Embedded C++ Ecosystem 55
Technical requirements .................................................................................................... 56
Compilers and development environments ...................................................................... 56
Arm Keil MDK and Arm Compiler for Embedded • 58
IAR C/C++ Compiler and IAR Embedded Workbench for Arm • 59
Vendor-supported IDEs and GCC • 60
GCC • 60
Compiler Explorer • 62
Static analyzers ................................................................................................................. 64
Unit testing ....................................................................................................................... 68
Profiling ............................................................................................................................ 73
Summary .......................................................................................................................... 75
Join our community on Discord ........................................................................................ 75
Chapter 4: Setting Up the Development Environment for a
C++ Embedded Project 77
Technical requirements .................................................................................................... 78
Requirements for a modern software development environment ..................................... 78
Compiler • 78
Build automation • 79
Simulator • 80
Code editor • 80
Containerized development environment ........................................................................ 81
Building the Hello, World! program using CMake • 83
Building a firmware using CMake • 86
Containerized development environment and Visual Studio Code ................................... 87
Summary .......................................................................................................................... 91
Part II: C++ Fundamentals 93
Chapter 5: Classes – Building Blocks of C++ Applications 95
Technical requirements .................................................................................................... 96
Encapsulation ................................................................................................................... 96
Setters and getters • 98
Static methods • 99
Structs • 100
Storage duration and initialization .................................................................................. 101
Non-static member initialization • 102
Default member initializers • 102
Constructors and member initializer lists • 102
Converting constructors and explicit specifiers • 104
Static member initialization • 106
Inheritance and dynamic polymorphism ........................................................................ 108
Virtual functions • 110
Virtual function implementation • 111
UML class diagrams • 113
Dynamic polymorphism • 114
Summary ......................................................................................................................... 116
Join our community on Discord ....................................................................................... 116
Chapter 6: Beyond Classes – Fundamental C++ Concepts 117
Technical requirements ................................................................................................... 117
Namespaces ..................................................................................................................... 118
Unnamed namespaces • 120
Nested namespaces • 120
Function overloading ....................................................................................................... 121
Interoperability with C .................................................................................................... 123
External and Language Linkage in C++ • 124
C standard library in C++ • 124
References ........................................................................................................................ 125
Value categories • 125
Lvalue references • 127
Rvalue references • 127
Standard library containers and algorithms .................................................................... 129
Array • 129
Container adaptors • 131
Algorithms • 132
std::copy and std::copy_if • 132
std::sort • 133
Summary ......................................................................................................................... 134
Chapter 7: Strengthening Firmware – Practical C++
Error Handling Methods 135
Technical requirements ................................................................................................... 136
Error codes and asserts .................................................................................................... 136
Global error handlers • 139
Asserts • 141
Exceptions ....................................................................................................................... 145
std:: optional and std::expected ....................................................................................... 149
Summary ......................................................................................................................... 152
Join our community on Discord ....................................................................................... 152
Part III: C++ Advanced Concepts 153
Chapter 8: Building Generic and Reusable Code with Templates 155
Technical requirements ................................................................................................... 156
Template basics ............................................................................................................... 156
Making a call to the template function • 157
Template specialization • 159
Template metaprogramming .......................................................................................... 160
Concepts ......................................................................................................................... 164
Compile-time polymorphism ......................................................................................... 166
Using Class Templates for Compile-Time Polymorphism • 166
Curiously recurring template pattern (CRTP) • 168
Summary ........................................................................................................................ 170
Chapter 9: Improving Type-Safety with Strong Types 171
Technical requirements ................................................................................................... 172
Implicit conversion .......................................................................................................... 172
Numeric promotions and conversions • 174
Array-to-pointer conversion • 178
Function-to-pointer conversion • 180
Explicit conversion .......................................................................................................... 181
const_cast • 181
static_cast • 182
dynamic_cast • 185
reinterpret_cast • 187
Type punning • 189
Type punning – the correct way • 191
Strong types ..................................................................................................................... 192
Summary ........................................................................................................................ 198
Join our community on Discord ...................................................................................... 198
Chapter 10: Writing Expressive Code with Lambdas 199
Technical requirements ................................................................................................. 200
Lambda expression basics .............................................................................................. 200
Storing lambdas using std::function ............................................................................... 203
The command pattern • 206
GPIO interrupt manager • 207
std::function and dynamic memory allocation ................................................................ 212
Summary ......................................................................................................................... 214
Chapter 11: Compile-Time Computation 215
Technical requirements ................................................................................................... 215
Templates ........................................................................................................................ 216
constexpr specifier .......................................................................................................... 218
Example 1 – MAC address parser • 220
Example 2 – Generating a lookup table • 223
Generating a lookup table • 227
Writing a signal representing the Steinhart-Hart equation • 230
Analyzing the usage example firmware code • 234
consteval specifier .......................................................................................................... 235
Summary ........................................................................................................................ 237
Join our community on Discord ...................................................................................... 237
Part IV: Applying C++ to Solving Embedded Domain
Problems 239
Chapter 12: Writing C++ HAL 241
Technical requirements .................................................................................................. 242
Memory-mapped peripherals ......................................................................................... 242
CMSIS memory-mapped peripherals • 242
Memory-mapped peripherals in C++ • 244
Type-safe memory-mapped peripherals in C++ • 247
Modeling HSION and HSITRIM bit fields from the RCC register • 249
Generic versions of hsion and hsi_trim • 252
Timers ............................................................................................................................. 253
Summary ........................................................................................................................ 258
Chapter 13: Working with C Libraries 259
Technical requirements .................................................................................................. 259
Using C HAL in C++ projects ............................................................................................ 260
UART interface for flexible software design • 260
The UART interface in the Adapter pattern • 264
Introducing static classes ................................................................................................ 265
Using RAII for wrapping the littlefs C library .................................................................. 267
LittleFS – a filesystem for microcontrollers • 268
Introducing an RAII-based C++ wrapper • 271
Cleaner file management with RAII • 274
Summary ........................................................................................................................ 275
Join our community on Discord ...................................................................................... 275
Chapter 14: Enhancing Super-Loop with Sequencer 277
Technical requirements .................................................................................................. 278
Super-loop and motivation for a sequencer .................................................................... 278
Designing a sequencer .................................................................................................... 280
Storing a callable ............................................................................................................ 283
Implementing a sequencer ............................................................................................. 287
Summary ........................................................................................................................ 290
Chapter 15: Practical Patterns – Building a Temperature Publisher 291
Technical requirements .................................................................................................. 292
The Observer pattern ...................................................................................................... 292
Runtime implementation ............................................................................................... 294
Compile-time implementation ....................................................................................... 297
Leveraging variadic templates • 298
Improving the compile-time implementation • 302
Summary ........................................................................................................................ 304
Join our community on Discord ...................................................................................... 304
Chapter 16: Designing Scalable Finite State Machines 305
Technical requirements .................................................................................................. 306
FSM – a simple implementation ..................................................................................... 306
Describing states and events • 308
Tracking current state and handling events – the FSM class • 309
Using the ble_fsm class • 311
Analyzing the output • 312
FSM – implementation using the State pattern ................................................................ 313
Understanding state class interfaces • 313
Refactoring the ble_fsm class • 316
Implementing the State pattern • 317
State design pattern • 319
State pattern implementation using tag dispatching ...................................................... 320
Boost SML ....................................................................................................................... 322
Chapter 17: Libraries and Frameworks 327
Technical requirements .................................................................................................. 328
Standard library .............................................................................................................. 328
Freestanding and hosted implementations in GCC • 328
Numeric and math • 329
<cstdint> • 329
<limits> • 329
<cmath> • 330
Containers and algorithms • 330
std::array • 330
std:: priority_queue • 330
std:: span • 330
Iterators • 331
Algorithms • 332
Template metaprogramming • 332
Parts of the standard library to avoid in embedded applications • 333
Embedded template library ............................................................................................ 333
Fixed-size containers • 334
Storing a callable with etl::delegate • 334
Other utilities provided by ETL • 334
Pigweed .......................................................................................................................... 335
Pigweed’s Sense tutorial • 335
RPC and Protocol Buffers • 340
Compile-time Initialization and Build ............................................................................ 343
Using CIB in a temperature publisher example • 344
Extending the temperature publisher example • 346
Summary ........................................................................................................................ 350
Chapter 18: Cross-Platform Development 351
Technical requirements ................................................................................................... 351
Importance of writing portable code .............................................................................. 352
SOLID design principles .................................................................................................. 352
Single Responsibility Principle (SRP) • 356
Open/Closed Principle (OCP) • 357
The Liskov Substitution Principle (LSP) • 357
The Interface Segregation Principle (ISP) • 357
The Dependency Inversion Principle (DIP) • 357
Testability ....................................................................................................................... 358
Summary ......................................................................................................................... 361
Join our community on Discord ...................................................................................... 362
Why subscribe? ............................................................................................................... 363
Other Books You May Enjoy 365
Index 369