100% found this document useful (1 vote)
51 views

Real-Time C++: Efficient Object-Oriented and Template Microcontroller Programming Christopher Kormanyos instant download

The document is a promotional and informational overview of the book 'Real-Time C++: Efficient Object-Oriented and Template Microcontroller Programming' by Christopher Kormanyos, focusing on the fourth edition which includes updates for C++20. It highlights new features, improved examples, and companion code available online, aiming to assist students and practitioners in utilizing C++ for microcontroller programming. Additionally, it lists other related programming books available for download from the same website.

Uploaded by

fletamumme0b
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
51 views

Real-Time C++: Efficient Object-Oriented and Template Microcontroller Programming Christopher Kormanyos instant download

The document is a promotional and informational overview of the book 'Real-Time C++: Efficient Object-Oriented and Template Microcontroller Programming' by Christopher Kormanyos, focusing on the fourth edition which includes updates for C++20. It highlights new features, improved examples, and companion code available online, aiming to assist students and practitioners in utilizing C++ for microcontroller programming. Additionally, it lists other related programming books available for download from the same website.

Uploaded by

fletamumme0b
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Real-Time C++: Efficient Object-Oriented and

Template Microcontroller Programming Christopher


Kormanyos install download

https://ebookmeta.com/product/real-time-c-efficient-object-
oriented-and-template-microcontroller-programming-christopher-
kormanyos/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Object Oriented Programming with Swift 2 1st Edition


Gastón C Hillar

https://ebookmeta.com/product/object-oriented-programming-with-
swift-2-1st-edition-gaston-c-hillar/

OBJECT ORIENTED PROGRAMMING First Edition M A. Ansari

https://ebookmeta.com/product/object-oriented-programming-first-
edition-m-a-ansari/

Python 3 Object oriented Programming Building robust


and maintainable software with object oriented design
patterns in Python 2nd Edition Phillips

https://ebookmeta.com/product/python-3-object-oriented-
programming-building-robust-and-maintainable-software-with-
object-oriented-design-patterns-in-python-2nd-edition-phillips/

Chase Fulton 20 The Abandoned Chase 1st Edition Cap


Daniels

https://ebookmeta.com/product/chase-fulton-20-the-abandoned-
chase-1st-edition-cap-daniels/
Play Date 1st Edition Emkay Connor

https://ebookmeta.com/product/play-date-1st-edition-emkay-connor/

Bound to the Cowboy A Small Town Off Limits Romance


Farrah Jane

https://ebookmeta.com/product/bound-to-the-cowboy-a-small-town-
off-limits-romance-farrah-jane/

Ukraine And Russia From Civilized Divorce To Uncivil


War 1st Edition Paul D’Anieri

https://ebookmeta.com/product/ukraine-and-russia-from-civilized-
divorce-to-uncivil-war-1st-edition-paul-danieri/

Conversation Analytic Research on Learning in Action


The Complex Ecology of Second Language Interaction in
the wild Educational Linguistics Book 38 John
Hellermann Søren W Eskildsen Simona Pekarek Doehler
Arja Piirainen Marsh
https://ebookmeta.com/product/conversation-analytic-research-on-
learning-in-action-the-complex-ecology-of-second-language-
interaction-in-the-wild-educational-linguistics-book-38-john-
hellermann-soren-w-eskildsen-simona-pekarek-doe/

Artificial Intelligence and the Arts: Computational


Creativity, Artistic Behavior, and Tools for Creatives
1st Edition Penousal Machado

https://ebookmeta.com/product/artificial-intelligence-and-the-
arts-computational-creativity-artistic-behavior-and-tools-for-
creatives-1st-edition-penousal-machado/
Management of Subarachnoid Hemorrhage

https://ebookmeta.com/product/management-of-subarachnoid-
hemorrhage/
Christopher Kormanyos

Real-Time
C++
Efficient Object-Oriented and Template
Microcontroller Programming
Fourth Edition
Real-Time C++
Christopher Kormanyos

Real-Time C++
Efficient Object-Oriented and Template
Microcontroller Programming

Fourth Edition
Christopher Kormanyos
Reutlingen
Germany

ISBN 978-3-662-62995-6 ISBN 978-3-662-62996-3 (eBook)


https://doi.org/10.1007/978-3-662-62996-3

© Springer-Verlag GmbH Germany, part of Springer Nature 2013, 2015, 2018, 2021
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of
the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology
now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publisher, the authors, and the editors are safe to assume that the advice and information in this book
are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or
the editors give a warranty, expressed or implied, with respect to the material contained herein or for any
errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer-Verlag GmbH, DE, part of
Springer Nature.
The registered company address is: Heidelberger Platz 3, 14197 Berlin, Germany
To those who pursue the art of technical
creativity
Preface to the Fourth Edition

C++20, the newest evolution of C++, adds various major new language features
that can significantly simplify and clarify program expression. At the same time,
using C++ in microcontroller programming is steadily gaining popularity and the
methods of its use are maturing in the embedded systems community. These steps
are matched by the widespread support of modern post-C++11,14,17 adherence
delivered by many high-quality microcontroller compiler vendors.
The fourth edition of this book keeps up with these progressions in C++. In
addition to covering new C++ language elements, particular emphasis is placed
on improving and extending the depth of the examples. Several interesting sample
projects requiring additional chips and exercising advanced software and laboratory
techniques have been added. Furthermore, one of the new computationally intensive
examples has also been adapted to both our target with the 8-bit microcontroller as
well as to a modern single-board computer with a powerful 32-bit processor.
These efforts are intended to widen the scope of applicability of this book for
students, practitioners, and hobbyists alike by exemplifying practical, hands-on
methods to leverage the power of portable C++ with lean, efficient real-time code.

New or Significantly Modified Sections

The fourth edition of this book contains several new or significantly modified parts.
These include:
• Section 1.10 adapted to add detailed comments regarding using rein-
terpret_cast sparingly,
• Section 3.2 extended to include example chapter03_02 that calculates prime
numbers and provides an insightful preview of numerous C++ techniques,
• Section 3.21 (new) on std::span from C++20’s <span> library that can be
used for delimiting pointer ranges,

vii
viii Preface to the Fourth Edition

• Section 3.22 (new) briefly showing how to use the <random> library for
generating sequences of pseudo-random integers,
• Section 4.4 which has been significantly expanded to include two full detailed
examples exercising dynamic polymorphism with an intuitive LED class hierar-
chy,
• Chapters 4, 7, and 8 which have been reworked in order to improve code
sequences and clarity of text passages,
• Section 5.13 (new) describing how to make effective and powerful use of
template integer sequences at compile time with std::integer_sequence,
• Section 6.14 with the addition of example chapter06_14 extending the
original CRC32 calculation of example chapter06_01 to make use of custom
ROM-based iterators and containers specifically designed for accessing read-
only program code,
• Section 6.21 (new) quantifying potential resource consumption resulting from
using runtime type information (RTTI),
• Section 9.5 has been reworked to implement a portable, all-software SPITM driver
subsequently used in examples chapter04_04, chapter04_04a, chap-
ter10_08, chapter10_08a, chapter10_09, and chapter16_08,
• Section 10.8 (new) providing a detailed example that uses external SRAM ICs to
calculate up to 100, 001 decimal digits of π with an application architecture that
uses custom SRAM pointers, iterators and containers, and numerical algorithms,
• Section 10.9 (new) which adapts the π calculations of Sect. 10.8 to the powerful
32-bit Arm® -based Raspberry Pi® Zero WH single-board computer system,
• Section 11.7 has been modified to include a sample that exemplifies preemptive
multitasking scheduling,
• Section 12.2 has been slightly√ expanded to include common standardized
mathematical constants such as 2, π , log 2, e, etc. in the <numbers> header,
• Section 16.7 (new) describing a portable implementation of big integer types
such as uint128_t, uint256_t, uint512_t, etc.,
• Section 16.8 (new) which develops a basic hardware-based custom random
engine that can serve as an efficient and practical, hobby-quality drop-
in replacement for std::default_random_engine and also presents
example chapter16_08 which performs primality testing of random 128-bit
big integers,
• Section 16.9 (new) on the freestanding implementation,
• Section A.9 enlarged to treat C++20 enhancements of lambda expression syntax
including template parameter lists and new capture style for this,
• Section A.16 broadened to include std::variant from C++20 in the new
<variant> addition to the STL,
• Section A.18 (new) covering a three-way comparison with the co-called space-
ship operator within the context of generalized equality and inequality,
Preface to the Fourth Edition ix

Improved or New Examples and Code Snippets

Several new examples have been added. All of the example projects have been
modernized and checked for compatibility with GCC version 10.1.0 built for
avr-g++. The portability and range of use of each example project have been
improved. In particular, test and verification of the examples have been carried
out with various GCC versions ranging from 5 through 9 using the language
standards flags -std=c++11, -std=c++14, -std=c++17, and -std=c++20
(as available).
☞ The chapter03_02 sample project (new) in Sect. 3.2 uses fixed-size integer
types and various other C++ techniques to compute the first 100 prime numbers.
☞ The chapter04_04 and chapter04_04a sample projects (new) in
Sect. 4.4 exercise various forms of polymorphism and class relationships through
the example of an LED class hierarchy.
☞ The chapter06_14 sample project (new) in Sect. 6.14 shows how to create
custom ROM-based iterators and containers used to calculate a CRC32 check-
sum.
☞ The sample projects chapter10_08 and chapter10_08a (new, advanced)
found in Sect. 10.8 use external memory ICs to extend available SRAM to
up to 2 Mbyte for calculations of as many as 100, 001 decimal digits of the
mathematical constant π .
☞ The chapter10_09 sample project (new, advanced) in Sect. 10.9 adapts the π
calculations of example chapter10_08a to the well-known 32-bit Arm® -
based Raspberry Pi® Zero WH single-board computer system, running OS-less in
bare metal mode. Seamlessly porting this application’s C++ algorithms from an
8-bit platform to a high-performance 32-bit Arm® –based system provides keen
insight into effective cross development on multiple systems.
☞ The chapter11_07 sample project (new, advanced) exemplifies intuitive
use of a preemptive multitasking scheduler constrained by small RAM/ROM
resource footprint.
☞ The chapter16_08 sample project (new, advanced) in Sect. 16.8 computes
128-bit prime numbers using a Miller–Rabin primality test.
With the fourth edition of this book, the detailed code snippets available in the
public domain now cover approximately two-thirds of code samples in the text. Each
code snippet comprises a complete and portable, single-file C++ program. Every
program can be compiled and run on a PC or easily adapted to a microcontroller
environment.
To obtain run-ability on a PC, code snippets have usually been embellished with
a main() subroutine. Some code snippets have been augmented with <thread>
support, simulated hardware registers or other C++ mechanisms in order to elucidate
the topic of the program. Outputs of the code snippets are typically printed
to the console with <iostream> and potentially formatted with the help of
<iomanip>. File names of the code snippets correspond to chapter and section
numbers in the book.
x Preface to the Fourth Edition

Companion Code

Based on new and reworked material in the fourth edition, the companion code has
been significantly improved and extended.

The entire companion code can be found here:


http://github.com/ckormanyos/real-time-cpp

The complete reference application is at:


http://github.com/ckormanyos/real-time-cpp/tree/master/ref_app

Example projects are stored here:


http://github.com/ckormanyos/real-time-cpp/tree/master/examples

Code snippets are located at:


http://github.com/ckormanyos/real-time-cpp/tree/master/code_snippets

Further Notes on Coding Style

The coding style in the fourth edition of this book stays consistent with that used
in the first through third editions. The code is intended to be easy to read and
straightforward to comprehend while simultaneously utilizing the full spectrum of
C++’s traditional and modern features.

Reutlingen, Germany Christopher Kormanyos


November 2020
Updated Trademarks
and Acknowledgments

In the prefaces to first and third editions, several trademarks and acknowledgments
are listed. Meanwhile, the authors/holders of certain trademarks/copyrights and the
scope of some of the acknowledgments have changed.
• Microchip® and AVR® are registered trademarks of Microchip Technology
Incorporated or its subsidiaries in the USA and other countries.
• ARDUINO® is a registered trademark of the Arduino Group.
• Arm® , Arm11TM and Arm1176JZF-STM are trademarks or registered trademarks
of Arm Limited (or its subsidiaries) in the USA and/or elsewhere.
• The word AUTOSAR is a registered trademark of the AUTOSAR Development
Partnership.
• Cypress® and MoBL® are registered trademarks of Cypress Semiconductor
Corporation. At the time of writing the fourth edition, Cypress is an Infineon
Technologies Company.
• Broadcom® is a registered trademark of Broadcom Corporation and/or its
affiliates in the USA, certain other countries, and/or the EU.
• Raspberry Pi® is a registered trademark of the Raspberry Pi Foundation.
• SPITM is a trademark of Motorola, Inc.
• LCD character displays used in various examples including chapter10_-
08a, chapter10_09, and chapter16_08 and pictured in the associated
Figs. 10.2, 10.4 and 16.4 are products of Newhaven Display International that are
bound by the terms and conditions provided at Newhaven Display International’s
Internet website.
• Several other trademarks are associated with electronic components that appear
prominently in some of the figures. These components and trademarks include
74xx logic ICs in Figs. 10.4 and 16.4 from Harris® Corp. Semiconductor Sector,
an LM2903 dual voltage comparator in Fig. 16.4 from FairchildTM Semiconduc-
tor International, Inc., electrolytic capacitors in various figures from Vishay®
Roederstein, potentiometers in various figures from Piher Sensing Systems
(an Amphenol® company), an SMD-to-DIP adapter of type PA0208 with text
PROTO-ADVANTAGE.COM in Fig. 10.2, and a micro SD card inserted in a

xi
xii Updated Trademarks and Acknowledgments

tray in Fig. 10.4 from Transcend® Information, Inc. All these and any other
trademarks mentioned or shown in the figures are the property of their respective
companies.
• Nonetheless this is neither an official publication of nor has it been authorized,
sponsored, or approved by any of the aforementioned copyright authors, copy-
right holders, or their subsidiaries.
• The circuits of all target hardware described and depicted in various chapters
and appendices have been designed and assembled on solderless prototyping
breadboards by myself.
• All photographs of target hardware shown in various chapters and appendices
were taken by myself.
Preface to the Third Edition

C++ is a modern, expressive object-oriented programming language that continues


to evolve. In keeping up with the exciting development of C++, the third edition of
this book has been updated for C++17.1
With this iteration of the language, the purpose of this book remains the same—
to show through example and text how to leverage C++’s powerful object-oriented
and template features in the realm of microcontroller programming with the goal of
improving software quality and robustness while simultaneously fulfilling efficiency
requirements.
Several new sections have been added and others have been modified or adapted.
These changes cover new language elements and library features in C++17. They
also reflect the trend of improved compiler support for C++11 and C++14.
More errors have been identified, predominantly reported by careful and patient
readers. All errors that have been found have been corrected.

New or Significantly Modified Sections

The third edition of this book contains several new or significantly modified
sections. These include:
• Section 2.2 updated for a newer GCC toolchain with a more simple decorated
name (i.e., GCC version 7.2.0 built for the target avr-g++).
• Section 3.4 adding information on C++17 nested namespace definitions,
• Section 3.17 now including descriptions of the (in the second edition of this book
missing) standardized suffixes if, i, and il from the <complex> library,
• Section 3.18 (new) detailing the specifiers alignof and alignas,

1 Atthe time of writing the third edition of this book, state-of-the-art compilers support C++17.
The specification process is ongoing, and some language experts predict that C++20 will be the
next revision of the C++ standard, potentially available in 2020.

xiii
xiv Preface to the Third Edition

• Section 3.19 (new) for the specifier final,


• Section 3.20 (new) on defining types with C++11 alias,
• Section 9.8 (new) portraying a full example that animates an RGB LED to
produce a colorful light display,
• Section 12.4 covering inclusion of additional mathematical special functions in
<cmath> specified in the C++17 standard,
• several sections in Chap. 13 reflecting improvements of the fixed_point class
in the companion code,
• Section 16.6 (new) presenting an extended-complex template class that promotes
the functionality of the <complex> library to user-defined types other than
float, double, and long double,
• Chapter 17 (new) showing how to use C code in a C++ project (hereby
“Additional Reading” has been moved from Chaps. 17 to 18),
• the tutorial of Appendix A, in particular Sect. A.4 updating static_assert
for C++17, Sect. A.15 (new) about the <type_traits> library, Sect. A.16
(new) on using std::any from the C++17 <any> library, and Sect. A.17 (new)
introducing structured binding declarations (also from C++17).

Improved or New Examples and Code Snippets

All sample projects have been modernized for GCC version 7.2.0 built for
avr-g++, and five new examples have been added.
☞ The chapter06_01 sample project (new) shows step-by-step how to perform
the benchmark of the CRC calculation described in Sects. 6.1 and 6.2.
☞ The chapter09_07 example in Sect. 9.7 has been adapted to architectural
improvements found in the new chapter09_08 sample of Sect. 9.8,
☞ The chapter09_08 sample project (new) animates an industry-standard off-
the-shelf RGB LED. This example incorporates several real-time C++ features
including object-oriented design, peripheral driver development, and multitask-
ing. They are merged together within the context of a coherent, intuitive, and
visible project. By means of simulation on a PC, the chapter09_08 sample
also exemplifies cross-development and methods for creating portable code.
☞ The chapter12_04 example (new) performs highly detailed calculations of
several mathematical special functions. These are used to provide a benchmark
of floating-point operations.
☞ The chapter17_03 sample project (new) takes an existing C library used
for CRC calculations and wraps the procedural functions in classes that can be
employed in object-oriented C++. This practical exercise shows how to leverage
the power of valuable existing C code within a modern C++ project.
☞ The chapter17_03a sample project (new) uses the CRC classes of the
chapter17_03 example and distributes the work of the calculations among
successive time slices in a multitasking environment.
Preface to the Third Edition xv

With the third edition of this book, code snippets have been made available in the
public domain. The code snippets correspond to certain code samples that appear
in the text. Each code snippet comprises a complete and portable, single-file C++
program. Every program can be compiled and run on a PC or easily adapted to a
microcontroller environment.
To obtain run-ability on a PC, code snippets have been embellished with a
main() subroutine. Some code snippets have been augmented with <thread>
support or other higher-level mechanisms in order to elucidate the topic of the
program. Outputs are printed to the console with <iostream>. The file names
of the code snippets correspond to chapter and section numbers in the book.

Companion Code

The companion code has been improved and extended based on new and reworked
sections of the third edition. Contemporary compiler toolchains are used. Legacy
directories that previously provided for certain aspects of C++11 compatibility have
been removed, as modern compilers now support these.

The entire companion code can be found here:


http://github.com/ckormanyos/real-time-cpp

The reference application is at:


http://github.com/ckormanyos/real-time-cpp/tree/master/ref_app

Example projects can be found here:


http://github.com/ckormanyos/real-time-cpp/tree/master/examples

Code snippets are located at:


http://github.com/ckormanyos/real-time-cpp/tree/master/code_snippets

Further Notes on Coding Style

The coding style in the third edition of this book stays consistent with that used in the
first and second editions. The code is intended to be easy to read and straightforward
to comprehend while simultaneously utilizing the full spectrum of C++’s traditional
and modern features.
xvi Preface to the Third Edition

Updated Trademarks and Acknowledgments

In the preface to first edition of this book, we listed several trademarks and
acknowledgments. Meanwhile the authors/holders of certain trademarks/copyrights
and the scope of some of the acknowledgments have changed.
• MICROCHIP® , ATMEL® , and AVR® are registered trademarks of Microchip
Technology Incorporated or its subsidiaries in the USA and other countries.
• Real-Time C++: Efficient Object-Oriented and Template Microcontroller Pro-
gramming, Third Edition is a book authored by Christopher Kormanyos and
published by Springer Verlag and has not been authorized, sponsored, or
otherwise approved of by Microchip Technology Incorporated.
• ARDUINO® is a registered trademark of the Arduino Group.
• The word AUTOSAR is a registered trademark of the AUTOSAR Development
Partnership.
• The circuits of all target hardware described in this book and depicted in various
chapters such as Chaps. 2, 9, and Appendix D, were designed and assembled on
solderless prototyping breadboards by Christopher Kormanyos.
• All photographs of target hardware in this book shown in chapters including
Chaps. 2, 9, Appendix D and any others were taken by Christopher Kormanyos.

Reutlingen, Germany Christopher Kormanyos


February 2018
Preface to the Second Edition

C++ seamlessly blends object-oriented techniques with generic template methods,


creating a modern powerful programming language useful for problem-solving in
countless domains. The most recent evolution of C++ from C++11 to C++14 has
brought yet further improvements to this rich language.1 As C++ becomes even
more expressive, growing numbers of embedded systems developers are discovering
new and fascinating ways to utilize its multifaceted capabilities for creating efficient
and effective microcontroller software.
The second edition of this book retains its original purpose to serve as a practical
guide to programming real-time embedded microcontroller systems in C++. New
material has been incorporated predominantly reflecting changes introduced in
the C++14 standard. Various sections have been reworked according to reader
suggestions. Selected passages have been reformulated in a continued effort to
improve clarity. In addition, all known errors throughout the text have been
corrected.
New sections have been added (in particular for C++14) covering:
• digit separators (Sect. 3.15),
• binary literals (Sect. 3.16),
• user-defined literals (Sect. 3.17),
• variable templates (Sect. 5.12),
• and the chapter09_07 sample project (Sect. 9.7) controlling an industry-
standard seven-segment display.
Two new sample projects, chapter02_03a and chapter09_07, have been
added to the companion code.

1 At the time of writing the second edition of this book, C++14 is brand new. World-class compilers

are shipped with support for C++14. Work is in progress on C++1z, the next specification of C++
(sometimes known as C++17). Experts anticipate that the specification of C++1z could be finished
in 2017.

xvii
xviii Preface to the Second Edition

☞ The chapter02_03a sample project implements LED toggling at 1/ 2 Hz


with timing provided by a simple multitasking scheduler in combination with a
timer utility.
☞ The chapter09_07 sample project in the newly added Sect. 9.7 uses many of
the advanced programming methods in this book to animate an industry-standard
seven-segment display.
Significantly reworked or corrected parts of this book include:
✓ corrections and clarifications in Chap. 1 on getting started with C++,
✓ the description of the chapter02_02 project in Sect. 2.2,
✓ parts of Chap. 3 on the jump-start in real-time C++,
✓ corrections and clarifications in Chap. 5 on templates,
✓ Sects. 6.1 and 6.2 on optimization and performance,
✓ parts of Chap. 10 on custom memory management,
✓ parts of Chaps. 12 and 13 on mathematics,
✓ the literature list in Sect. 18.1,
✓ parts of Appendix A in the C++ tutorial,
✓ and repairs and extensions of the citations in some chapter references.

Companion Code

The companion code continues to be supported and numerous developers have


successfully worked with it on various cross-development platforms. The scope of
the companion code has been expanded to include a much wider range of target
microcontrollers. In addition, the chapter02_03a and chapter09_07 sample
projects that are mentioned above have been added to the companion code.

The companion code is available at:


http://github.com/ckormanyos/real-time-cpp

More Notes on Coding Style

The second edition of this book features slight changes in coding style. These can
be encountered in the code samples throughout the text.
Compiler support for standard C99 and C++11 macros of the form UINT8_C(),
UINT16_C(), UINT32_C(), etc. and corresponding macros for signed types in
the <stdint.h> and <cstdint> headers has become more prevalent (see also
Sect. 3.2). Consequently, these macros are used more frequently throughout the code
samples.
Preface to the Second Edition xix

These macros are useful for creating integer numeric literal values having
specified widths. The code below, for example, utilizes UINT8_C() to initialize
an 8-bit integer variable with a numeric literal value.

#include <cstdint>

std::uint8_t byte_value = UINT8_C(0x55);

Digit separators have become available with C++14 (Sect. 3.15). These are used
in selected code samples to improve clarity of long numeric literals. Digit separators
are shown in the code sample below.

#include <cstdint>

constexpr std::uint32_t prime_number =


UINT32_C(10’006’721);

constexpr float pi = 3.1415926535’8979323846F;

Other than these minor changes, however, the coding style in the second edition
of this book remains consistent with that of the first edition and is intended to be
clean and clear.

Reutlingen, Germany Christopher Kormanyos


Seattle, Washington
May 2015
Preface to the First Edition

This book is a practical guide to programming real-time embedded microcontroller


systems in C++. The C++ language has powerful object-oriented and template
features that can improve software design and portability while simultaneously
reducing code complexity and the risk of error. At the same time, C++ compiles
highly efficient native code. This unique and effective combination makes C++ well-
suited for programming microcontroller systems that require compact size, high
performance, and safety-critical reliability.
The target audience of this book includes hobbyists, students, and professionals
interested in real-time C++. The reader should be familiar with C or another pro-
gramming language and should ideally have had some exposure to microcontroller
electronics and the performance and size issues prevalent in embedded systems
programming.

About This Book

This is an interdisciplinary book that includes a broad range of topics. Real-


world examples have been combined with brief descriptions in an effort to provide
an intuitive and straightforward methodology for microcontroller programming
in C++. Efficiency is always in focus, and numerous examples are backed up with
real-time performance measurements and size analyses that quantify the true costs
of the code down to the very last byte and microsecond.
Throughout the chapters, C++ is used in a bare-bones, no-frills fashion without
relying on any libraries other than those specified in the language standard itself.
This approach facilitates portability.
This book has three parts and several appendices. The three parts generally build
on each other with the combined goal of providing a coherent and effective set of
C++ methods that can be used with a wide range of embedded microcontrollers.

xxi
xxii Preface to the First Edition

• Part I provides a foundation for real-time C++ by covering language technolo-


gies. Topics include getting started in real-time C++, object-oriented methods,
template programming, and optimization. The first 3 chapters have a particularly
hands-on nature and are intended to boost competence in real-time C++.
Chapter 6 has a unique and important role in that it is wholly dedicated to
optimization techniques appropriate for microcontroller programming in C++.
• Part II presents detailed descriptions of a variety of C++ components that are
widely used in microcontroller programming. These components can be either
used as presented, or adapted for other projects. This part of the book uses some
of C++’s most powerful language elements, such as class types, templates, and
the STL, to develop components for microcontroller register access, low-level
drivers, custom memory management, embedded containers, multitasking, etc.
• Part III describes mathematical methods and generic utilities that can be
employed to solve recurring problems in real-time C++.
• The appendices include a C++ language tutorial, information on the real-time
C++ development environment, and instructions for building GNU GCC cross-
compilers and a microcontroller circuit.
C++ is a rich language with many features and details, the description of
which can fill entire bookshelves. This book, however, primarily concentrates on
how to use C++ in a real-time microcontroller environment. Along those lines,
C++ language tutorials have been held terse, and information on microcontroller
hardware and compilers is included only insofar as it is needed for the examples.
A suggested list of additional reading material is given in Chap. 18 for those
seeking supplementary information on C++, the C++ standard library and STL,
software design, C++ coding guidelines, the embedded systems toolchain, and
microcontroller hardware.
When units are needed to express physical quantities, the MKS (meter, kilogram,
second) system of units is used.

Companion Code, Targets, and Tools

The companion code includes three introductory projects and one reference project.
The introductory projects treat various aspects of the material presented in Chaps. 1
and 2. The reference project is larger in scope and exercises many of the methods
from all the chapters.
The companion code is available at:
http://github.com/ckormanyos/real-time-cpp
The C++ techniques in this book specifically target microcontrollers in the small-
to-medium size range. Here, small-to-medium spans the following approximate size
and performance ranges.
• 4 kbyte . . . 1 Mbyte program code
• 256 byte . . . 128 kbyte RAM
Preface to the First Edition xxiii

• 8-bit . . . 32-bit CPU


• 8 MHz . . . 200 MHz CPU frequency
Most of the methods described in this book are, however, scalable. As such, they
can be used equally well on larger or smaller devices, even on PCs and workstations.
In particular, they can be employed if the application has strict performance and size
constraints.
A popular 8-bit microcontroller clocked with a frequency of 16 MHz has been
used as the primary target for benchmarking and testing the code samples in
this book. Certain benchmarks have also been performed with a well-known 32-
bit microcontroller clocked at 24 MHz. An 8-bit microcontroller and a 32-bit
microcontroller have been selected in order to exercise the C++ methods over a
wide range of microcontroller performance.
All the C++ examples and benchmarks in the book and the companion code
have been compiled with GNU GCC versions 4.6.2 and 4.7.0. Certain examples and
benchmarks have also been compiled with other PC-based compilers.
The most recent specification of C++11 in ISO/IEC 14882:2011 is used
throughout the text. At the time this book is written, the specification of C++11
is brand new. The advent of C++11 has made C++ significantly more effective and
easy-to-use. This will profoundly influence C++ programming. The well-informed
reader will, therefore, want to keep in touch with C++11 best practice as it evolves
in the development community.

Notes on Coding Style

A consistent coding style is used throughout the examples in this book and in the
companion code.
Code samples are written with a fixed-width font. C++ language key-
words and built-in types use the same font, but they are in boldface. For instance,

constexpr int version = 7;

In general, the names of all symbols such as variables, class types, members, and
subroutines are written in lower case. A single underscore ( _ ) is used to separate
words and abbreviations in names. For instance, a system-tick variable expressed
with this style is shown in the code sample below.

unsigned long system_tick;

Using prefixes, suffixes, or abbreviations to incorporate type information in a


name, sometimes known as Hungarian notation, is not done. Superfluous prefixes,
xxiv Preface to the First Edition

suffixes, and abbreviations in Hungarian notation may obscure the name of a


symbol, and symbol names can be more intuitive and clear without them. For
example,

std::uint16_t name_of_a_symbol;

Names that are intended for use in public domains are preferentially long and
descriptive rather than short and abbreviated. Here, clarity of expression is preferred
over terseness. Symbols used for local subroutine parameters or private implementa-
tion details with obvious meanings, however, often have terse or abbreviated names.
The global subroutine below, for example, uses this naming style. It returns the
float value of the squared Euclidean distance from the origin of a point in two-
dimensional Cartesian space R2 .

float squared_euclidean_distance(const float& x,


const float& y)
{
return (x * x) + (y * y);
}

C++ references are heavily used because this can be advantageous for small
microcontrollers. Consider an 8-bit microcontroller. The work of copying subrou-
tine parameters or the work of pushing them onto the stack for anything wider
than 8-bits can be significant. This workload can potentially be reduced by using
references. In the previous code sample, for instance, the floating-point subroutine
parameters x and y, each four bytes wide, have been passed to the subroutine by
reference (i.e., const float&).
Fixed-size integer types defined in the std namespace of the C++ standard
library such as std::uint8_t, std::uint16_t, std::uint32_t, and the
like are preferentially used instead of plain built-in types such as char, short,
int, etc. This improves clarity and portability. An unsigned login response with
exactly 8 bits, for instance, is shown below.

std::uint8_t login_response;

Code samples often rely on one or more of the C++ standard library head-
ers such as <algorithm>, <array>, <cstdint>, <limits>, <tuple>,
<vector>, etc. In general, code samples requiring library headers do not explicitly
include their necessary library headers.
Preface to the First Edition xxv

The declaration of login_response above, for example, actually requires


<cstdint> for the definition of std::uint8_t. The library file is, however,
not included. In general, the code samples focus on the core of the code, not on the
inclusion of library headers.
It is easy to guess or remember, for example, that std::array can be found
in <array> and that std::vector is located <vector>. It can, however, be
more difficult to guess or remember that std::size_t is in <cstddef> or that
std::accumulate() is in <numeric>. With assistance from online help and
other resources and with a little practice, though, it becomes routine to identify what
standard library parts can be found in which headers.
In cases for which particular emphasis is placed on the inclusion of a header file,
the relevant #include line(s) may be explicitly written. For instance,

#include <cstdint>

std::uint8_t login_response;

Namespaces are used frequently. In general, though, the using directive is not
used to inject symbols in namespaces into the global namespace. This means that
the entire namespace must be typed with the name of a symbol in it. This, again,
favors non-ambiguity over brevity.
The unsigned 16-bit counter below, for example, uses a type from the std
namespace. Since the “using namespace std” directive is not used, the name
of the namespace (std) is explicitly included in the type.

std::uint16_t counter;

Suffixes are generally appended to literal constant values. When a suffix is


appended to a literal constant value, its optional case is uppercase. For example,

constexpr float pi = 3.14159265358979323846F;

constexpr std::uint8_t login_key = 0x55U;

Certain established C++ coding guidelines have strongly influenced the coding
style. For the sake of terseness and clarity, however, not every guideline has been
followed all the time.
xxvi Preface to the First Edition

One clearly recognizable influence of the coding guidelines is the diligent use of
C++-style casts when converting built-in types. The following code, for instance,
explicitly casts from float to an unsigned integer type.

float f = 3.14159265358979323846F;

std::uint8_t u = static_cast<std::uint8_t>(f);

Even though explicit casts like these are not always mandatory, they can resolve
ambiguity and eliminate potential misinterpretation caused by integer promotion.
Another influence of the coding guidelines on the code is the ordering of class
members according to their access level in the class. The communication class
below, for example, represents the base class in a hierarchy of communication
objects. The members in the class definition are ordered according to access level.
In particular,

class communication
{
public:
virtual ~communication();

virtual bool send(const std::uint8_t) const;


virtual bool recv(std::uint8_t&);

protected:
communication();

private:
bool recv_ready;
std::uint8_t recv_buffer;
};

C-style preprocessor macros are used occasionally. Preprocessor macros are


written entirely in uppercase letters. Underscores separate the words in the names of
preprocessor macros. The MAKE_WORD() preprocessor macro below, for example,
creates an unsigned 16-bit word from two unsigned 8-bit constituents.

#define MAKE_WORD(lo, hi) \


(uint16_t) (((uint16_t) (hi) << 8) | (lo))
Preface to the First Edition xxvii

Acknowledgments

First and foremost, I would like to thank my wife and my daughter for encouraging
me to write this book and also for creating a peaceful, caring atmosphere in which I
could work productively. Thank you for your support and your time. You have my
gratitude.
I would also like to express appreciation to family, friends, and associates, too
numerous to list, who contributed to this project with their innovative ideas, support,
friendship, and companionship.
Thanks go to the members of the C++ standards committee, Boost, the volunteers
at GCC and all the developers in the vibrant C++, and embedded systems commu-
nities. Through your efforts, often times for no pay whatsoever, C++ has evolved
to an unprecedented level of expressiveness, making object-oriented and generic
programming more effective and easier than ever.
Working with Springer Verlag was a delightful experience. I thank my editor,
who first identified the merit of this work and supported me throughout the writing
process. I also thank the copy editing team and all the staff at Springer Verlag for
their professionalism and capable assistance.
• ATMEL® and AVR® are registered trademarks of Atmel Corporation or its
subsidiaries, in the USA and other countries.
• Real-Time C++: Efficient Object-Oriented and Template Microcontroller Pro-
gramming is a book authored by Christopher Kormanyos and published by
Springer Verlag and has not been authorized, sponsored, or otherwise approved
of by Atmel Corporation.
• ARDUINO® is a registered trademark of the Arduino Group.
• SPITM is a trademark of Motorola Corporation.
• The circuit of the target hardware described in this book and depicted in Chap. 2
and Appendix D was designed and assembled on a solderless prototyping
breadboard by Christopher Kormanyos.
• The photographs of the target hardware described in this book and depicted in
Chap. 2 and Appendix D were taken by Christopher Kormanyos.

Reutlingen, Germany Christopher Kormanyos


Seattle, Washington
September 2012
Contents

Part I Language Technologies for Real-Time C++


1 Getting Started with Real-Time C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1 The LED Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 The Syntax of C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Class Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5 Objects and Instances. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.6 #include . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.8 C++ Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.9 The main() Subroutine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.10 Low-Level Register Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.11 Compile-Time Constant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2 Working with a Real-Time C++ Program on a Board. . . . . . . . . . . . . . . . . . 21
2.1 The Target Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2 Build and Flash the LED Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.3 Adding Timing for Visible LED Toggling. . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.4 Run and Reset the LED Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.5 Recognizing and Handling Errors and Warnings. . . . . . . . . . . . . . . . . . . 28
2.6 Reaching the Right Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3 An Easy Jump Start in Real-Time C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.1 Declare Locals When Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.2 Fixed-Size Integer Types and Prime Number Example . . . . . . . . . . . . 36
3.3 The bool Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.4 Organization with Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.5 Basic Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.6 Basic Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

xxix
xxx Contents

3.7 nullptr Replaces NULL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


3.8 Generalized Constant Expressions with constexpr . . . . . . . . . . . . 49
3.9 static_assert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.10 Using <limits> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.11 std::array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
3.12 Basic STL Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.13 <numeric> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.14 atomic_load() and atomic_store() . . . . . . . . . . . . . . . . . . . . . 55
3.15 Digit Separators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.16 Binary Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.17 User-Defined Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.18 Using alignof and alignas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
3.19 The Specifier final . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
3.20 Alias as an Alternative to typedef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3.21 Delimiting Pointer Ranges with <span> . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.22 Generating Random Numbers with <random> . . . . . . . . . . . . . . . . . . . 64
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4 Object-Oriented Techniques for Microcontrollers . . . . . . . . . . . . . . . . . . . . . . 69
4.1 Object Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.2 Objects and Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.3 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4.4 Dynamic Polymorphism and a Detailed LED Example . . . . . . . . . . . 77
4.5 The Real Overhead of Dynamic Polymorphism . . . . . . . . . . . . . . . . . . . 84
4.6 Pure Virtual and Abstract. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.7 Class Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.8 Non-copyable Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
4.9 Constant Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.10 Static Constant Integral Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
4.11 Class Friends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.12 Virtual Is Unavailable in the Base Class Constructor . . . . . . . . . . . . . . 97
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
5 C++ Templates for Microcontrollers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
5.1 Template Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
5.2 Template Scalability, Code Re-Use and Efficiency . . . . . . . . . . . . . . . . 103
5.3 Template Member Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
5.4 Template Class Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.5 Template Default Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
5.6 Template Specialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
5.7 Static Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
5.8 Using the STL with Microcontrollers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
5.9 Variadic Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
5.10 Template Metaprogramming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
5.11 Tuples and Generic Metaprogramming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
5.12 Variable Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Contents xxxi

5.13 Template Integer Sequences. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132


References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
6 Optimized C++ Programming for Microcontrollers . . . . . . . . . . . . . . . . . . . . 137
6.1 Use Compiler Optimization Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
6.2 Know the Microcontroller’s Performance . . . . . . . . . . . . . . . . . . . . . . . . . . 141
6.3 Know an Algorithm’s Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
6.4 Use Assembly Listings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
6.5 Use Map Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
6.6 Understand Name Mangling and De-mangling . . . . . . . . . . . . . . . . . . . . 145
6.7 Know When to Use Assembly and When Not to . . . . . . . . . . . . . . . . . . 147
6.8 Use Sensible Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
6.9 Simplify Code with typedef and Alias . . . . . . . . . . . . . . . . . . . . . . . . . . 149
6.10 Use Native Integer Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
6.11 Use Scaling with Powers of Two. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
6.12 Potentially Replace Multiply with Shift-and-Add . . . . . . . . . . . . . . . . . 156
6.13 Consider Advantageous Hardware Dimensioning . . . . . . . . . . . . . . . . . 156
6.14 Consider ROM-ability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
6.15 Minimize the Interrupt Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
6.16 Use Custom Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
6.17 Use the STL Consistently . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
6.18 Use Lambda Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
6.19 Use Templates and Scalability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
6.20 Use Metaprogramming to Unroll Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
6.21 Potential Costs of Runtime Type Information (RTTI) . . . . . . . . . . . . . 171
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

Part II Components for Real-Time C++


7 Accessing Microcontroller Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
7.1 Defining Constant Register Addresses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
7.2 Using Templates for Register Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
7.3 Generic Templates for Register Access. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
7.4 Bit-Mapped Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
8 The Right Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
8.1 The Startup Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
8.2 Initializing RAM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
8.3 Initializing the Static Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
8.4 The Connection Between the Linker and Startup . . . . . . . . . . . . . . . . . . 196
8.5 Understand Static Initialization Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
8.6 Avoid Using Uninitialized Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
xxxii Contents

8.7 Jump to main() and Never return. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202


8.8 When in main(), What Comes Next?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
9 Low-Level Hardware Drivers in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
9.1 An I/O Port Pin Driver Template Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
9.2 Programming Interrupts in C++. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
9.3 Implementing a System Tick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
9.4 A Software PWM Template Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
9.5 A Serial SPITM Driver Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
9.6 CPU-Load Monitors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
9.7 Controlling a Seven-Segment Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
9.8 Animating an RGB LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
10 Custom Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
10.1 Dynamic Memory Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
10.2 Using Placement-new . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
10.3 Allocators and STL Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
10.4 The Standard Allocator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
10.5 Writing a Specialized ring_allocator . . . . . . . . . . . . . . . . . . . . . . . . 244
10.6 Using ring_allocator and Other Allocators . . . . . . . . . . . . . . . . . 247
10.7 Recognizing and Handling Memory Limitations . . . . . . . . . . . . . . . . . . 249
10.8 Off-Chip Memory and Computing 100,001 Digits of π . . . . . . . . . . . 251
10.9 Using Ample RAM on Arm® -Based Single-Board Computer . . . . 266
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
11 C++ Multitasking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
11.1 Multitasking Schedulers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
11.2 Task Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
11.3 The Task Control Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
11.4 The Task List. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
11.5 The Scheduler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
11.6 Extended Multitasking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
11.7 Preemptive Multitasking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
11.8 The C++ Thread Support Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292

Part III Mathematics and Utilities for Real-Time C++


12 Floating-Point Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
12.1 Floating-Point Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
12.2 Mathematical Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
12.3 Elementary Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
12.4 Special Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Contents xxxiii

12.5 Complex-Valued Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312


12.6 Compile-Time Evaluation of Functions with constexpr . . . . . . . 316
12.7 Generic Numeric Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
13 Fixed-Point Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
13.1 Fixed-Point Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
13.2 A Scalable Fixed-Point Template Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
13.3 Using the fixed_point Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
13.4 Fixed-Point Elementary Transcendental Functions . . . . . . . . . . . . . . . . 338
13.5 A Specialization of std::numeric_limits . . . . . . . . . . . . . . . . . . 349
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
14 High-Performance Digital Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
14.1 A Floating-Point Order-1 Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
14.2 An Order-1 Integer Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
14.3 Order-N Integer FIR Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
14.4 Some Worked-Out Filter Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
15 C++ Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
15.1 The nothing Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
15.2 The noncopyable Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
15.3 A Template timer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
15.4 Linear Interpolation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
15.5 A circular_buffer Template Class . . . . . . . . . . . . . . . . . . . . . . . . . . 382
15.6 The Boost Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
16 Extending the C++ Standard Library and the STL . . . . . . . . . . . . . . . . . . . . 389
16.1 Defining the Custom dynamic_array Container . . . . . . . . . . . . . . . 389
16.2 Implementing and Using dynamic_array . . . . . . . . . . . . . . . . . . . . . . 392
16.3 Writing Parts of the C++ Library if None Is Available . . . . . . . . . . . . 396
16.4 Implementation Notes for Parts of the C++ Library and STL . . . . . 396
16.5 Providing now() for <chrono>’s High-Resolution Clock . . . . . . 405
16.6 Extended-Complex Number Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
16.7 An Embeddable Big Integer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
16.8 Customizing <random>. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
16.9 Freestanding Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
17 Using C-Language Code in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
17.1 Accessing C Language Code in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
17.2 An Existing C-Language CRC Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
17.3 Wrapping the C-Based CRC Library with C++ Classes . . . . . . . . . . . 430
17.4 Return to Investigations of Efficiency and Optimization . . . . . . . . . . 433
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
xxxiv Contents

18 Additional Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435


18.1 Literature List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437

A A Tutorial for Real-Time C++. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439


A.1 C++ Cast Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
A.2 Uniform Initialization Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
A.3 Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
A.4 Compile-Time Assert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
A.5 Numeric Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
A.6 STL Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
A.7 STL Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
A.8 STL Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
A.9 Lambda Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
A.10 Initializer Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
A.11 Type Inference and Type Declaration with auto
and decltype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
A.12 Range-Based for(:) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
A.13 Tuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
A.14 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
A.15 The <type_traits> Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
A.16 Using std::any and std::variant . . . . . . . . . . . . . . . . . . . . . . . . . . 471
A.17 Structured Binding Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
A.18 Three-Way Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475

B A Robust Real-Time C++ Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477


B.1 Addressing the Challenges of Real-Time C++ . . . . . . . . . . . . . . . . . . . . . 477
B.2 Software Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
B.3 Establishing and Adhering to Runtime Limits . . . . . . . . . . . . . . . . . . . . . 480
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481

C Building and Installing GNU GCC Cross Compilers. . . . . . . . . . . . . . . . . . . 483


C.1 The GCC Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
C.2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
C.3 Building GMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
C.4 Building MPFR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
C.5 Building MPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
C.6 Building PPL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
C.7 Building ISL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
C.8 Building the Binary Utilities for the Cross Compiler . . . . . . . . . . . . . . 488
C.9 Building the Cross Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
C.10 Using the Cross Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
Contents xxxv

D Building a Microcontroller Circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493


D.1 The Circuit Schematic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
D.2 Assembling the Circuit on a Breadboard . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496

Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Acronyms

C C represents the set of complex numbers in mathematics.


R R represents the set of real numbers on the real axis in mathematics.
R2 R2 represents two-dimensional Cartesian space in mathematics and
geometry.
R3 R3 represents three-dimensional Cartesian space in mathematics and
geometry.
Z Z represents the set of integer numbers in mathematics.
ADC Analog-Digital Converter.
ASCII American Standard Code for Information Interchange [25] is a
numerical representation of characters, often used in areas such as
computer programming and telecommunication.
AUTOSAR AUTomotive Open System ARchitecture [2] is a worldwide coopera-
tion of automotive manufacturers and companies supplying electron-
ics, semiconductors and software that concentrates on, among other
things, a standardized architecture for automotive microcontroller
software.
AWG American Wire Gauge.
binutils Binary Utilities [6] are the GNU binary utilities such as archiver,
assembler, linker, object file parsers, etc. for GCC.
C C is the C programming language, which is often referred to as
ANSI–C [1] or C89 [2]. Later versions of C include C99 [13] and
C11 [17].
C99 C99 refers to the C programming language, as specified in ISO/IEC
9899:1999 [13].
C11 C11 refers to the C programming language, as specified in ISO/IEC
9899:2011 [17].
C++ C++ refers to the C++ programming language.
C++98 C++98 refers to the C++ programming language, as specified in
ISO/IEC 14882:1998 [12].
C++03 C++03 refers to the C++ programming language, as specified in
ISO/IEC 14882:2003 [15].

xxxvii
xxxviii Acronyms

C++11 C++11 refers to the C++ programming language, as specified in


ISO/IEC 14882:2011 [18].
C++14 C++14 refers to the C++ programming language, as specified in
ISO/IEC 14882:2014 [19].
C++17 C++17 refers to the C++ programming language, as specified in
ISO/IEC 14882:2017 [20].
C++20 C++20 [26] is predicted by some C++ language experts to be the
next revision of the C++ standard, possibly to become available in
the year 2020.
CLooG Chunky Loop Generator [4] is a software library used for geometric
polyhedron analysis.
CRC Cyclic Redundancy Check [27].
CPU Central-Processing Unit.
ctor constructor of a class object in object-oriented programming is a
special subroutine that is called when an object is created.
DIL Dual In-Line electronic component packaging.
DSP Digital Signal Processor.
dtor destructor of a class object in object-oriented programming is a
special subroutine that is called when an object is destroyed or
deleted.
FIR Finite-Impulse Response is a kind of digital filter.
FLASH Flash Memory is a nonvolatile computer memory that can be electri-
cally written and erased. Flash is commonly used as an alternative to
ROM.
FPU Floating-Point Unit implements floating-point arithmetic in hard-
ware. Many modern high-performance microcontrollers use an FPU
to accelerate floating-point calculations.
GAS is the GNU ASsembler.
GCC GNU Compiler Collection [7] is a collection of free compilers for
several popular programming languages including, among others,
C and C++. GCC is supported for a wide range of targets.
GMP GMP is the GNU Multiple-Precision library [9]. It implements highly
efficient multiple-precision representations of integer and floating-
point data types.
GNU Is a ∗nix-like computer operating system consisting entirely of free
software [8].
GUI Graphical User Interface.
HEX Hexadecimal representation is a base-16 numerical representation
commonly used to store program data in computer engineering.
ICE In-Circuit Emulator is a highly sophisticated hardware device used to
debug embedded microcontroller software with an emulated bond-
out processor.
ISL Integer Set Library [11] is a software library used for manipulating
sets of integers.
Acronyms xxxix

ISP In-System-Programming is the act of programming the program


code of a microcontroller using a communication interface while the
microcontroller is fitted in the application, rather than as a standalone
non-soldered component.
ISR Interrupt Service Routine.
JTAG Joint Test Action Group, later standardized as IEEE 1149.1 [10], is a
protocol and hardware interface used for printed circuit board testing,
boundary scan and recently more and more for debugging embedded
systems.
LED Light-Emitting Diode is a semiconductor-based light source used in
diverse applications such as lighting, consumer electronics, and toys.
MCAL Microcontroller Abstraction Layer is a low-level layer in a lay-
ered software architecture (such as AUTOSAR). The interface of
the MCAL is typically written in a portable fashion. The MCAL
implementation itself, however, contains partially non-portable com-
ponents that access microcontroller peripherals and their registers,
such as PWM signal generators, timers, serial UARTs, and other
communication interfaces.
MinGW Minimalist GNU [21] is an open-source programming toolset that
emulates ∗nix-like environments.
MKS Meter, Kilogram, Second is a system of units used to express physical
quantities.
MPC Multiple-Precision Complex [22] is a GNU C library that implements
multiple-precision arithmetic of complex numbers.
MPFR Multiple-Precision Floating-Point with correct Rounding [5, 23] is
the GNU multiple-precision floating-point library. It is built on top of
GMP and places special emphasis on efficiency and correct rounding.
MSYS Minimal SYStem [21] is a collection of GNU utilities that enhance
and extend the MinGW shell.
newlib newlib [24] is a free implementation of the C standard library. It is
well-suited for use with embedded systems and has been ported to a
variety of CPU architectures.
nop No OPeration is a common assembly instruction that simply does no
operation. One or more nops are often chained sequentially in order
to be used for ultra low-level functions such as creating very short
delays or flushing an instruction pipeline.
opcode OPeration CODE is a machine language instruction containing the
operation to be done.
PC Personal Computer.
POSIX Portable Operating System Interface is an open standardized operat-
ing system specified in ISO/IEC 9945:2003 [14].
PPL Parma Polyhedra Library [3] is a software library for abstract geo-
metrical polyhedron representations.
PWM Pulse-Width Modulated signal is a square wave that usually has a
fixed period and a variable duty cycle.
xl Acronyms

RAM Random Access Memory is computer memory with nearly constant


access time regardless of address or memory size. RAM is volatile in
the sense that data are typically lost when the power is switched off.
ROM Read-Only Memory is a class of computer memory that, once
written, can only be modified with external programming tools—or
not be modified at all. ROM has permanent character in the sense that
data are retained throughout power on/off cycles.
SPITM Serial Peripheral Interface bus is a four-wire serial communication
interface commonly used for communication between a microcon-
troller and one or more off-chip devices on the printed circuit board.
STL Standard Template Library is part of the C++ standard library.
The standard template library contains a vast collection of generic
containers, iterators and algorithms.
TO–220 Transistor Outline electronic component packaging, number 220.
TR1 C++ Technical Report 1 includes the standard library extensions
that are specified in ISO/IEC TR 19768:2007 [16]. TR1 has been
predominantly integrated in C++11 (ISO/IEC 14882:2011 [18]).
UART Universal Asynchronous Receiver/Transmitter is an asynchronous
receiver and transmitter commonly used for serial communication
between a PC and a microcontroller.

References

1. ANSI, ANSI X3.159-1989 American National Standard for Information Systems – Program-
ming Language C (American National Standard for Information, New York, 1989)
2. AUTOSAR, Automotive Open System Architecture (2017), http://www.autosar.org
3. BUGSENG, Parma Polyhedra Library (PPL) (2012), http://www.bugseng.com/products/ppl
4. CLooG, Chunky Loop Generator (2015), http://www.cloog.org
5. L. Fousse, G. Hanrot, V. Lefèvre, P. Pélissier, P. Zimmermann, MPFR: a multiple-precision
binary floating-point library with correct rounding. ACM Trans. Math. Soft. 33(2) (2007).
Article 13
6. Free Software Foundation, GNU Binutils (2011), http://www.gnu.org/software/binutils
7. Free Software Foundation, GNU Compiler Collection (2015), http://gcc.gnu.org
8. Free Software Foundation, GNU Operating System (2015), http://gnu.org
9. GMP, GNU Multiple Precision Arithmetic Library (2012), http://gmplib.org
10. IEEE Computer Society, IEEE Std 1149.1 – 1990: IEEE Standard Test Access Port and
Boundary-Scan Architecture (1990). Available at http://standards.ieee.org/findstds/standard/
1149.1-1990.html
11. ISL, Integer Set Library (2015), http://isl.gforge.inria.fr
12. ISO/IEC, ISO/IEC 14882:1998 : Programming languages – C++ (International Organization
for Standardization, Geneva, 1998)
13. ISO/IEC, ISO/IEC 9899:1999 : Programming languages – C (International Organization for
Standardization, Geneva, 1999)
14. ISO/IEC, ISO/IEC 9945:2003 : Information Technology – Portable Operating System Inter-
face (POSIX) (International Organization for Standardization, Geneva, 2003)
15. ISO/IEC, ISO/IEC 14882:2003 : Programming languages – C++ (International Organization
for Standardization, Geneva, 2003)
Acronyms xli

16. ISO/IEC, ISO/IEC TR 19768:2007 : Information technology – Programming languages –


Technical Report on C++ Library Extensions (International Organization for Standardization,
Geneva, 2007)
17. ISO/IEC, ISO/IEC 9899:2011 : Programming languages – C (International Organization for
Standardization, Geneva, 2011)
18. ISO/IEC, ISO/IEC 14882:2011 : Information technology – Programming languages – C++
(International Organization for Standardization, Geneva, 2011)
19. ISO/IEC, ISO/IEC 14882:2014 : Information technology – Programming languages – C++
(International Organization for Standardization, Geneva, 2014)
20. ISO/IEC, ISO/IEC 14882:2017 : Programming languages – C++ (International Organization
for Standardization, Geneva, 2017)
21. MinGW, Home of the MinGW and MSYS Projects (2012), http://www.mingw.org
22. MPC, GNU MPC (2012), http://www.multiprecision.org
23. MPFR, GNU MPFR Library (2013), http://www.mpfr.org
24. Red Hat, newlib (2013), http://sourceware.org/newlib
25. Wikipedia, ASCII (2017), http://en.wikipedia.org/wiki/ASCII
26. Wikipedia, C++20 (2017), http://en.wikipedia.org/wiki/C%2B%2B20
27. Wikipedia, Cyclic Redundancy Check (2017), http://en.wikipedia.org/wiki/Cyclic_
redundancy_check
Part I
Language Technologies for Real-Time C++
Chapter 1
Getting Started with Real-Time C++

C++ programs combine class types that encapsulate objects with procedural subrou-
tines in order to embody the functionality of the application. This chapter presents
these main language elements of C++ using a short, intuitive program that toggles
an LED on a microcontroller output port pin. In addition, other language features
are introduced including the syntax of C++, namespaces, the C++ standard library
and optimization with compile time constants. This chapter uses our target system
with the 8-bit microcontroller.

1.1 The LED Program

A simple microcontroller application is shown in Fig. 1.1 on the following page.


The circuit in this figure has one LED connected to a digital output port pin on
the microcontroller over a resistor to ground. Switching the port pin to high drives
current through the resistor and the LED, and thereby switches the LED on. Setting
the port pin to low stops current flow through the resistor and the LED, subsequently
turning the LED off.
The LED circuit shown in Fig. 1.1 is part of the circuit belonging to our target
system with the 8-bit microcontroller. Further details on the entire circuit in this
application and its electrical components can be found in the figure here and also in
Sect. 2.1 and Appendix D.
An object-oriented C++ program designed to control the LED circuit in Fig. 1.1
is shown below. It is called the LED program. In the LED program, an led object
called led_b5 is created on portb.5. The LED object led_b5 is subsequently
toggled from low to high and vice versa indefinitely without pause, break or return
in an iterative loop in the main() subroutine.

© Springer-Verlag GmbH Germany, part of Springer Nature 2021 3


C. Kormanyos, Real-Time C++, https://doi.org/10.1007/978-3-662-62996-3_1
4 1 Getting Started with Real-Time C++

Fig. 1.1 The circuit of the


LED D1 on our target with
the 8-bit microcontroller is
shown. D1 is connected to
portb.5 on microcontroller
pin 17 over a 750  resistor
R1 to ground

// chapter01_01-001_led_program.cpp

// The LED program.

#include <cstdint>
#include "mcal_reg.h"

class led
{
public:
// Use convenient class-specific typedefs.
typedef std::uint8_t port_type;
typedef std::uint8_t bval_type;

// The led class constructor.


led(const port_type p,
const bval_type b) : port(p),
bval(b)
{
// Set the port pin value to low.
*reinterpret_cast<volatile bval_type*>(port)
&= static_cast<bval_type>(~bval);

// Set the port pin direction to output.

// Note that the address of the port direction


// register is one less than the address
// of the port value register.
const port_type pdir = port - 1U;

*reinterpret_cast<volatile bval_type*>(pdir)
|= bval;
}
1.1 The LED Program 5

void toggle() const


{
// Toggle the LED via direct memory access.
*reinterpret_cast<volatile bval_type*>(port)
^= bval;
}

private:
// Private member variables of the class.
const port_type port;
const bval_type bval;
};

namespace
{
// Create led_b5 on portb.5.
const led led_b5
{
mcal::reg::portb,
mcal::reg::bval5
};
}

int main()
{
// Toggle led_b5 in a loop forever.
for(;;)
{
led_b5.toggle();
}
}

The LED program uses various C++ language elements. These include classes,
namespaces, type definitions, C++ cast operators, register access via direct memory
access and even a little bit of the C++ standard library.
In particular, the predominant parts of the LED program are:
• the inclusion of header files with #include,
• the led class,
• the led class constructor and class members that encapsulate the initialization
and toggling of the LED via direct memory access,
• the anonymous namespace containing the led_b5 object,
• and the main() subroutine that toggles the led_b5 object indefinitely in a
never-ending for(;;)-loop.
6 1 Getting Started with Real-Time C++

In the following sections of this chapter, we will investigate in detail how each
one of these parts of the LED program is written and how each one works. Along
the way, we will briefly discuss many aspects of the syntax of C++ and efficient
ways to use the C++ language with real-time embedded systems.

1.2 The Syntax of C++

The syntax of C++ is similar to that of C. In fact, C++ is based on C. With a few
minor exceptions, nearly all valid C language constructs can also be used in a C++
program.
As with C, the C++ language uses curly braces { ... } to delimit scope.
Parenthesizing and operator priorities are the same in C++ and C. The C++
language has familiar built-in types such as char, short, int, long, float,
double, etc. C++ also supports C’s well-known #include syntax for inclusion
of user-defined header files and standard library files.
C++ uses C’s iteration statements for, while and do-while. Source-level
comments in C++ can be written in either slash-slash form ( // ... ) or block
form ( /* ... */ ). Most C++ developers, however, preferentially use slash-slash
comments instead of C-style block comments. See also Item 4 in Meyers [4].

1.3 Class Types

Classes, structures (structs) and unions are class types in C++. The LED program
has a class called led. In particular,

class led
{
// ...
};

Class types enable object-oriented programming in C++ because they group data
together with functions operating on them in a self-contained entity. The led class,
for example, encapsulates the real LED hardware by grouping the LED’s port pin
together with its toggle function.
Classes, structures and unions typically have a mixture of data, functions and
overloaded operators called members. The public interface of the led class, for
instance, has a constructor (also known as a ctor) and a member function called
toggle().
1.3 Class Types 7

A class constructor has the same name as its containing class. Constructors
can have any number of input parameters. The constructor of led has two input
parameters. They characterize the address of the port data register and the bit-
position of the output port pin of the LED hardware.
Class initialization code can be placed in the body of the constructor. In
particular, the port hardware of the LED is initialized in the body of the led
constructor.

class led
{
public:
// The led class constructor.
led(const port_type p,
const bval_type b) : port(p),
bval(b)
{
// Set the port pin value to low.
*reinterpret_cast<volatile bval_type*>(port)
&= static_cast<bval_type>(~bval);

// Set the port pin direction to output.

// Note that the address of the port direction


// register is one less than the address
// of the port value register.
const port_type pdir = port - 1U;

*reinterpret_cast<volatile bval_type*>(pdir)
|= bval;
}
// ...
};

Here, the address of the LED’s port direction register is calculated from the
address of its port data register. In addition, the port pin value is set to low before
the port pin direction is set to output. This strategy eliminates potential spikes on
I/O pins. These kinds of electrical characteristics of I/O ports are specific to the
underlying microcontroller hardware and need to be modified when porting the led
class to another system.
8 1 Getting Started with Real-Time C++

The so-called constructor initialization list is placed after the constructor


function parameters and a colon, but before the opening brace of the constructor
body. In particular,

led(const port_type p,
const bval_type b) : port(p),
bval(b)
{
// ...
}

In the constructor initialization list of the led class here, for example, we
initialize the member variables port and bval with the corresponding values
supplied by the input parameters p and b.
Constant member variables must be initialized in the constructor initialization
list. Non-constant member variables should be initialized in the constructor initial-
ization list. The order of all member variables present in the constructor initialization
list should be identical to their order of appearance in the class definition because
the compiler initializes them in the order they are declared. See also Item 13 in
Meyers [4].
The implementation of the led class shown above is entirely contained within
its definition. Alternatively, part or all of the implementation of a class type can be
placed in a separate source file.
The definition of the led class, for instance, could be placed in a header file
called led.h. In other words,

// In the file led.h


class led
{
public:
led(const port_type p,
const bval_type b);

void toggle() const;


// ...
};

The corresponding implementation details of the led class could be put in the
led.cpp source file. For example,
1.3 Class Types 9

// In the file led.cpp


#include "led.h"

led::led(const port_type p,
const bval_type b) : port(p),
bval(b)
{
// Set the port pin value to low.
*reinterpret_cast<volatile bval_type*>(port)
&= static_cast<bval_type>(~bval);

// Set the port pin direction to output.

// Note that the address of the port direction


// register is one less than the address
// of the port value register.
const port_type pdir = port - 1U;

*reinterpret_cast<volatile bval_type*>(pdir)
|= bval;
}

void led::toggle() const


{
// Toggle the LED.
*reinterpret_cast<volatile bval_type*>(port)
^= bval;
}

// ...

When members are defined outside of a class definition, the scope resolution
operator (::) is used to resolve the class name from the names of members in the
implementation file. For example,

// The scope resolution operator (::).


void led::toggle() const
{
// ...
}

Including implementation details directly in the class definition can improve


optimization via inlining. There is no need to explicitly recommend inlining to the
Another Random Scribd Document
with Unrelated Content
those of her own age and standing so often kept aloof from her, as
having so little in common. “Laura—Mary—have pity on my
obtuseness.”
“Why, Lady Gresham’s long-talked-of fête is fixed at last; and of
course you will go. Your invitation was enclosed in mamma’s last
night. Absolutely her ladyship condescends to entreat her to
introduce you. I cannot imagine the reason of this sudden
empressement—she could have visited you long ago, had she
wished it.”
“She did wish it individually, I believe; but an unfortunate
misunderstanding between her brother and mine prevented it.
Edward has long wished the estrangement to cease, so I shall be
very happy to meet her half-way, and accept the invitation. When is
it?”
“Next Monday.”
“Monday! Why, to-day is Friday! You must mean Monday week.”
“Indeed I do not. How she will manage I cannot tell, except that
when people have more wealth than they know what to do with,
they can do what they please. Her villa at Richmond, too, is just the
place for a fête champétre; and the novel shortness of the invitation,
and being the day before a drawing-room, will crowd her rooms,
depend upon it. It is something unusually exciting, the very bustle of
the thing.”
“But I thought it was not to be until—”
“Until Herbert Gresham returned. Nor will it. He arrives to-morrow
night, or some time on Sunday, quite suddenly, not having been
expected for several weeks yet. What with his foreign honours, his
promised baronetcy, and last, not least, his distinguished
appearance, he will be sought and fêted by all the money-loving
mammas and husband-seeking daughters for the remainder of the
season.”
“The worst of its being a fête champétre is, that we must have
complete new dresses,” rejoined Laura. “And how to coax papa for
the necessary help, I know not; my last quarter was all gone before
I received it, and my debts actually frighten me. But what is to be
done? go I must.”
“And then the shortness of the notice!” continued Mary; “really
Lady Gresham might have given us more time. Who can decide what
to wear, or even what colour, in three days?”
“Come, Lucy, decide! But of course you will go!” exclaimed
Charlotte, impatiently. “It will be your first appearance in public this
season, and so you can have nothing to think about in the way of
expense. Nothing but the trouble of seeing about a new dress.”
“Which will prevent my going, much as I might wish it,” replied
Miss Neville, very quietly, though the faint tinge rising to her cheek,
and the quiver of the lip, might have betrayed some degree of
internal emotion.
“Prevent your going! What can you possibly mean?” exclaimed her
guests together.
“That as it is now six o’clock on Friday, and you tell me Lady
Gresham’s fête is three o’clock on Monday, I have not sufficient time
to procure all I want (for having been so long in mourning, I have
literally nothing that will do), without breaking a resolution, and
sacrificing a principle, which I do not feel at all inclined to do.”
“Sacrificing a principle! Lucy, you are perfectly ridiculous! What
has principle to do with a fête champétre? Your head is turned with
the stupid cant of oppressing, and the people, as if we had not
annoyances, and vexations, and pressure too, when we want more
money than we happen to have! And as for time, what is to prevent
your sending to Mrs. Smith to-night, (by-the-bye, how can you
employ an English artiste?) and get all you want by ten o’clock on
Monday morning? Why, I cannot even give, an order till after the
post comes in to-morrow. I must wait to know what was worn at the
Duchesse de Nemours’ fête champétre the other day. One feels just
out of the ark, in England.”
“And I am sure I cannot decide what to wear till then,” languidly
remarked Mary.
“And as for me, I am in a worse predicament than either of you,”
laughed Laura, but her laugh was not a gay one. “Raise the wind I
must, but it requires time to think how.”
We have no space to follow this conversation further. Persuasions,
reproaches, and taunts assailed Miss Neville on all sides, but she did
not waver. Charlotte left her in high dudgeon; Mary marvelled at her
unfortunate delusion, quite convinced that she was on the verge of
insanity; and Laura wishing that she could be but as firm. Not that
she comprehended or allowed the necessity of the principle on which
she acted, but only as it would save her the disagreeable task of
thinking how to get the necessary costume when both modiste and
jeweller had refused to trust her any more.
For nearly half an hour Lucy remained sitting where her visitors
had left her, her hands pressed on her eyes, and her whole posture
denoting a painful intensity of thought. Herbert Gresham returning!
His mother’s unexpected and pressing invitation! Could it be that the
bar between the families was indeed so entirely removed, that she
might hope as she had never dared hope before? Sir Sydney’s hatred
to her brother, from some political opposition, had been such, it was
whispered at the time, that he had obtained his nephew some
honourable appointment abroad, only because he feared that he not
only loved Lucy, but leaned towards Lord Valery’s political opinions.
Four years had passed since then, and Herbert Gresham was no
longer a cipher in another’s hands. He had formed his own
principles, marked out his own course; and Lucy heard his name so
often and so admiringly from her brother’s lips, that the dream of
her first season could not pass away, strive against it as she might,
for she knew not whether she claimed more than a passing thought
from him who held her being so enchained. And now he was
returning; and to the fête to welcome him she was invited, with such
an evident desire for her presence, that her heart bounded beneath
the thronging fancies that would come, seeming to whisper it was at
his instigation. And why could she not go? Was it not, indeed, a
quixotic and uncalled-for sacrifice? How could the resolution of one
feeble individual aid in removing the heavy pressure of over-work
from the thousands of her fellow-creatures? There was time, full
time, for all she required, if she saw about it at once. It was but
adding an atom to the weight of oppression, which, whether added
or withheld, could be of no moment; and surely, surely, for such a
temptation there was enough excuse. How would Herbert construe
her absence, if, indeed, it was at his wish the invitation came? Why
might she not——
“Lucy, seven o’clock and not ready for dinner! Why, what are you
so engrossed about?” exclaimed her brother, half-jestingly, half-
anxiously, the latter feeling prevailing, as she hastily looked up. A
few, a very few words, and he understood it all.
“And yet I know, even under such circumstances, you will not fail,”
he said; and how powerful is the voice of affectionate confidence in
the dangerous moment of hesitation between right and wrong? “You
may, indeed, be but one where there needs the aid of hundreds; but
if all hold back because they are but one, how shall we gain the
necessary muster? To check this thoughtless waste of human life,
this (in many) unconscious crushing of all that makes existence, is
WOMAN’S work. Man may legislate, may theorise, but he looks to his
female relatives for its practical fulfilment. Dearest, do you choose
the right, and trust me, useless as the sacrifice now seems, you will
yet thank God that it was made.”

Lady Gresham’s fête was brilliant, recherché—crowded as


anticipated. The weather was lovely, the gardens magnificent, the
arrangements in the best taste that an ultra-fashionist of some thirty
years’ experience could devise. Youth, beauty, rank, wealth, all were
there, and the female portion set off to the best advantage by an
elegance of costume and an extreme carefulness of attire, without
which all knew an entrance into Lady Gresham’s select coterie could
never be obtained. A despot in the empire of dress and appearance,
she little knew, and still less cared, for all the petty miseries (alas,
that such a word should be spoken in the same breath with dress!)
which her invitations usually excited. The resolve to outvie—the utter
carelessness of expenditure while the excitement lasted—the
depression, almost despair, at the accumulated debts which followed
—the rivalry of a first fashion—the petty manœuvres not to give a
hint of the intended costume, and the equally petty manœuvres to
discover it—the mortification when, after all the lavish expense, all
the mysteries, others appeared more fashionable, more recherché—
the disgust with which, in consequence, the previously considered
perfect dress was henceforth regarded—these, and a hundred other
similar emotions had been, during the “season,” called forth again
and again; and in beings destined for immortality! was it marvel they
had no thought for other than themselves?
That this fête was in commemoration of Herbert Gresham’s return,
and that he was present, the hero of the day, not a little increased
its excitement and importance. But he moved amongst his mother’s
guests with native and winning courtesy indeed, but as if his mind
were engrossed with other and deeper things. In the four years of
his absence many changes, powerful in themselves, but still only
invisibly working, had taken place in the political aspect of his
country. By means of private correspondence with the most
influential men of the day, and through the public journals, he had
felt the deepest interest in these changes; and from the very fact of
his looking on from a distance, and not mingling with the contending
waves of party, he had formed clearer views concerning them than
many on the spot. He had returned, determined to devote the whole
energies of his powerful mind to removing invisible oppression, so
lessening labour that MIND might resume her supremacy, and create
for every position its own immortal joys. He was no leveller of ranks;
no believer in that vain dream, equality. He had travelled and
thought much, and felt to his heart’s core the superiority of England
as a nation, both for constitution and morality; but this conviction,
instead of blinding him to her faults, quickened his perceptions, not
only regarding the evils, but their causes, and increased the intensity
of his desire to remove them.
It was not, however, only the habitude of thought which, on this
occasion, had given him a look of abstraction. He was disappointed.
His mother had told him that, in compliance with his desire, all
foolish coolness between his family and that of Lord Valery should
cease—she had condescended to make advances to Miss Neville,
which were coldly rejected. She did not tell him that these advances
had been merely an invitation to her fête (of whose sudden
arrangement Herbert was himself unconscious), and did not know
herself, and certainly would never have imagined the real reason of
Lucy’s refusal. Before the day closed, however, her son was destined
to be enlightened.
He was standing near a group of very gay young ladies and
gentlemen, conversing at first on grave topics with a friend, when
his quick ear was irresistibly attracted by the mention of Miss
Neville’s name, coupled with much satirical laughter.
“She will become a second Mrs. Fry, depend upon it,” was the
observation of one. “I should not be at all surprised that at last we
shall find her making pilgrimages through the streets of London, to
see if all the shops are closed at a certain hour, and the released
apprentices properly employed. She should set up an evening school
for drapers’ assistants and milliners’ apprentices. Why don’t you
propose it to her, Miss Balfour?”
Charlotte, whose superb Parisian costume gave her the triumph of
being almost universally envied, laughed, and declared it was too
much trouble.
“You stand in rather too much awe of both her and Lord Valery,”
was her brother’s rejoinder. “It is a pity, though, that Miss Neville has
imbibed such outré notions, otherwise she would be a nice girl
enough.”
“And did she really refuse to come only because the notice was
too short for her to get a proper costume without injuring or
oppressing—as the cant of the day has it—the poor milliners? How
perfectly ridiculous! I am sure the artistes who come for our orders
are in the finest condition both as to health and wealth.”
“And the shopmen—they are sleek, gay, care-nothing looking
fellows. As for their needing greater rest, more recreation,
opportunities to cultivate the mind, one has only to look at them to
feel the pure romance of the thing. What are some people born for
but to work?”
“And just imagine how dull London would be if all the shops were
closed by seven or eight o’clock! I should lose half my enjoyment in
walking to my club.”
“I should like to know what good Miss Neville and her party of
philanthropists think they will accomplish by giving so much liberty
and leisure. We shall have to build double the number of taverns, for
such will be their only resort. What can such people know of
intellectual amusement!”
“And if they did, what do they want with it? We should have a
cessation of all labour, and then what is to become of us, or the
country either?”
“It is pure folly. Some people must have a hobby to make a noise
about; and so now nothing is heard but oppression, internal slavery,
broken-hearted milliners’ apprentices, and maimed drapers’
assistants! Really, for so much eloquence, it is a pity they do not
choose a higher subject!”
“And I wish the present subject may never drop till the work is
done,” interposed Herbert Gresham, joining the conversation with a
suddenness, and speaking with such startling eloquence, that it
caused a general retreat of individual opinion. He would have been
amused had he felt less interested, to see the effect on both sexes
of his unexpected interference. He spoke very briefly, for he was too
disgusted with the littleness, the selfishness, of all he had heard to
attempt anything like argument. And the effort to excuse former
sentiments—to dare say he was right, but they had not reflected
much about it—thought it a pity to alter things which had been
going on so long—could not understand, even granting there was a
good deal of misery, how could it be helped, but if Herbert Gresham
thought it might be, no doubt there was more in it than they
believed, and very many other similar speeches, only excited his
contempt.
We must change the scene, for our space will not allow us more
than a slight sketch: a momentary glance, as it were, on things
passing daily, hourly around, and yet seen, known of, by how few!
Four or five days after Lady Gresham’s fête, Miss Neville might have
been seen entering one of those small, close, back streets, found
even in the aristocratic west, and whose dilapidated dwellings
present almost as great a contrast with the proud mansions which
surround and conceal them as the inhabitants themselves.
It was a poor old needlewoman whom Lucy was visiting, and,
surprised at finding her usual sitting-room empty, and fearing she
was ill—for there was no sign of work about, and Mrs. Miller was
infirm and ailing—she gently entered her sleeping apartment. The
rough bed was occupied indeed, but not by its usual inmate, who
was sitting by its side, tears rolling down her withered cheeks, and
her attention so fixed that she did not perceive Miss Neville’s
entrance. She was watching the painful, restless movements of a
girl, who, in a high state of delirium and fever, was lying on the
pallet; she was very young, and had been beautiful, but suffering
had scarcely left any trace but its own. Earnestly and pityingly, Lucy
entered into the sad, but only too common tale, her inquiries
elicited; but the old woman’s narration being garrulous and
unfinished, we will give it in our own words.
Fanny Roberts and Harry Merton, born and nurtured in the same
village, had been playmates, schoolfellows, friends, and at last lovers
—not only faithful and affectionate, but prudent and thoughtful. The
parents of both were poor, even in their humble village, but the
wishes and interests of their children were their first object, and to
see them somewhat higher in the world than themselves their sole
ambition. To set up an establishment in the neighbouring town,
combining linen-draper, dressmaker, and milliner, had been their day-
dream from the time they had conned their school lessons and taken
long walks together, instead of joining their playmates on the green;
and to fulfil this earnest wish, their parents, by many sacrifices,
which, measured by their love, seemed absolutely nothing, gathered
together sufficient to send them to London, and apprentice them
there. Harry was then nineteen and Fanny two years younger. Hope
was bright for both. Their only drawback seemed the impossibility of
meeting more than once a week; and six days of entire separation
was a weary interval to those accustomed to exchange affection’s
kindly words and looks each day. Only too soon, however, did the
oppressive reality of the present absorb the rosy hues of the future.
On the daily routine of unmitigated work, the exhausting labour, the
deadened energies, the absorption of every faculty in the depressing
weariness, we need not touch. It was no distaste for work, for both
had set to their respective duties with hearts burning to conquer
every difficulty—to do even more than was required of them, the
sooner to gain the longed-for goal; and had it not been for the
fearful burden of over-work, the absence of sufficient rest, of all
wholesome recreation, how brightly and nobly might these young
loving beings have walked the path of life, by mutual exertion
creating a home, and all the joys, which, in England that one word
speaks! Alas! ere eighteen months elapsed, every thought of
buoyancy and joy seemed strangely to have deserted Fanny. She
could not tell why, for outward things seemed exactly the same as
they had been at first. Harry was still faithful, still fond. Her heart
intuitively felt that he was altered. Why, she would often ask herself,
could she no longer feel happy? Why should every thought of her
own dear home cause such a sickly longing for fresh air and green
fields, that the hysteric sob would often rise choking in her throat,
and more than once, nothing but a timely burst of incomprehensible
tears had saved her from fainting as she sat. She could not satisfy
herself; but in reality it was the silent workings of insidious disease,
seeming mental, because impossible to be traced as physical, save
by the constant sensation of weariness, which she attributed merely
to sitting so long in close and crowded rooms; but though happiness
seemed gone, she retained the power of endurance; woman can and
will endure, but in nine cases out of ten, men cannot. In the one,
suffering often purifies; in the other, it but too often deteriorates.
Harry Merton had entered on his work joyfully and buoyantly,
determined to make the best of everything, and be good friends with
everybody. Naturally lively, with the power of very quick
acquirement, and a restless activity of mind as well as body, a very
few months’ trial convinced him that if he had not entirely mistaken
his vocation, he certainly must do something to make it more
endurable. He had heard of institutions for the people in London, of
amusements open even to the most economical; he had pictured
enjoying them with his Fanny, and gaining improvement likewise. He
found it all a dream. There were, indeed, such things, but not for
him or her. The hour of his release found not only every wholesome
amusement closed, but himself so weary, that mental recreation was
impossible, and yet with the yearning for some pleasure, some relief
from wearisome work, so natural in youth, stronger than ever. His
convivial, unsuspecting disposition led him to join the most
seemingly attractive, but in reality the most dangerous, of his
companions. The consequences need scarcely be narrated. He
became intemperate, gay, reckless, looking back on the pure, fresh
feelings of his early youth with wonder, and retaining but one of
their memories, his love for Fanny; but even that was no longer the
glad, hopeful feeling which it had been. He was constantly told, and
he saw, that it must be years before they could marry. He was
laughed at for imagining that either he or she would retain their
early feelings. He heard her beauty admired, and then pitied as a
most dangerous gift, which must eventually and most fearfully
separate her from him; and the most furious but most unfounded
jealousy took possession of him, and so darkened every hour of
meeting, that poor Fanny at length anticipated them with more
dread than pleasure. It was long, indeed, nearly three years, before
things came to such a crisis; but the gradual conviction of the
deterioration of her lover’s character was to Fanny the heaviest
suffering of all: that she still loved him, surely we need not say. She
saw the circumstances of this miserable change, not the change
itself. Her woman’s heart clung to him the more, from the very
anxiety he inspired. So intensely did she mourn for his long,
wearisome hours of joyless toil, that she scarcely felt her own;
though, when he was released at ten or eleven, she was often
working unceasingly till two in the morning. The choking cough, the
shortened breath, the aching spine, she scarcely felt, in the one
absorbing thought of him.
Whenever she could be spared, which in the “season” was very
seldom, it was Fanny’s custom to go to Mrs. Miller (her only friend in
London) Saturday night and remain till Sunday evening. Two or
three days before the invitations were out for Lady Gresham’s fête, a
note was given to her from Harry, the perusal of which occasioned
deeper suffering than anything she had yet endured. Snatching half
an hour from the scanty time allowed for sleep, the following was
her reply:—
“Harry! Harry! this from you! when you so fondly promised you
would never doubt me more! Yes, he did seek me that Saturday
night, or rather Sunday morning, for it was one o’clock; and I would
not have gone there, had you not made me promise that I would not
disappoint you, and that you would take me home. Why were you
not there? Why did you leave me to the chance of such a meeting?
And then upbraid me with putting myself in that bad man’s way! Oh,
Harry! Harry! by the memories of our early home, our early love,
spare me such unjust suspicion! You tell me writing will not satisfy
you, you must see me, hear from my own lips my version of this
cruel and most false tale. How can I see you till Saturday night, the
earliest, if then? Sunday if I can only crawl to Mrs. Miller’s, indeed I
will come, pain as it is now to move. Only trust me till then, dearest,
dearest Harry. Do not add to your burden and mine by thoughts like
these. You know that I am innocent; that I never have loved, never
can love, any one but you.”
The Sunday came, but Fanny was unable to keep her
engagement. Madame Malin was so overwhelmed with orders for
Lady Gresham’s fête, that even the Sabbath day was compelled to
be sacrificed. The peculiar trimmings which it was absolutely
necessary for Miss Balfour to have to complete the Parisian costume
(the details of which never arrived till eleven o’clock, Saturday, and
then all the materials had to be purchased) were Fanny’s work; and,
from her delicate taste, she, of all the assistants, could the least be
spared. In fact, extra hands were hired; for to complete twenty or
thirty full dresses from the noon of Saturday to ten o’clock Monday,
in addition to those already in hand for the drawing-room the
following day, was an unusual undertaking, even for the
indefatigable Madame Malin. Hour after hour those poor girls
worked,—through Saturday night, the yearned-for Sabbath, again
late into the night, till many fainted on their seats, and the miserable
toil was continued in a recumbent posture by those unable to sit
upright. A dead weight was on poor Fanny’s heart, a foreboding
misery; but the sufferings of the frame were such as almost to
deaden the agony of mind. The hour of release came at length,
inasmuch that, ill as she was, she craved permission to take home
some of the dresses, that she might call at Mrs. Miller’s on her way
back, and learn some news of Harry, and beseech her old friend to
seek him, and tell him the reason of her forced absence. Exhausted
and most wretched as she was, she had to wait till the dresses were
tried on—the capricious humour of the young ladies proved, by
altering, realtering, and final arrangement as they were originally—to
bear with petty fault-finding—until her whole frame seemed one
mass of nerve; and so detained, that she only entered the street
leading to her old friend’s abode, as the carriages whirled off their
elegantly-attired inmates to Lady Gresham’s fête.
What a tale awaited her! Harry, restless, miserable,—almost
maddened by the false reports against her,—and from the great
pressure of business in his master’s shop, from the innumerable
visits of modistes’ assistants to procure the necessary materials so
needed for the costumes of Mrs. Gresham’s fête, not released till
past one o’clock Sunday morning, had perambulated the streets all
night, in the vain hope of meeting Fanny, encountering one of his
jovial companions, who, half intoxicated, swore he had seen her
entering a coach with—Merton knew whom—and when collared and
shaken by the infuriated lover till he recovered his more sober
senses, declared he could not tell exactly, but he thought it was her:
at all events, Harry would know to-morrow, if she had gone as usual
to Mrs. Miller’s.
There she was not. Never before had six o’clock on Sunday
evening come without her presence; and really anxious, Mrs. Miller
(though not believing a syllable against her) conjured the unhappy
young man to call himself at Madame Malin’s, and inquire if she
were ill or detained. He did so. The well-instructed lacquey declared
the family were all at evening service, and if the apprentices were
not with their friends, he supposed they were there also; he knew
nothing about them; but he was quite sure his mistress never
permitted them to work on Sundays. Harry was in no state coolly to
consider his words. He rushed back like a madman to Mrs. Miller,
uttered a few incoherent sentences, and darted away before she had
time or thought even to reply. That very evening he enlisted, and the
Monday found him marching to Southampton with other troops
about to embark for India. A few lines to Mrs. Miller told her this,
and accompanied a parcel directed to Fanny, in case she should ever
see or hear of her again. The poor girl had just strength to tear it
open, to discover all her letters and formerly treasured gifts, even to
some withered flowers, returned, with a few words of stinging
reproach, bidding her farewell for ever, and dropped lifeless at the
old woman’s feet. One or two intervals of coherency enabled her, by
a few broken phrases, to explain the reason of her absence; but
brain fever followed, and even when Miss Neville saw her, all hope
was over. Vain was the skill of the gifted and benevolent physician
Lucy called in. Disease had been too long and too deeply rooted for
resistance to a shock which, in its agony, would have prostrated
even a healthy constitution. A few, a very few days of intense
suffering, and the crushed heart ceased to beat, the blighted frame
to feel, and misery for her was over. But for poor Harry—for the
parents of both—what might comfort them? We have seen the
deterioration of Harry’s character. There were many to mark and
condemn the faults, but none to perceive their cause. And when he
absconded from his apprenticeship, it did but bring conviction as to
his determined depravity. Who may tell the agony of those two
humble English homes, when the post brought the miserable news
of death to the one, and of sin and utter separation to the other?
They had not even the poor comfort of knowing the cause of their
son’s change; their own bold, free, happy, loving Harry,—how could
his parents associate him with sin?—or Fanny, the healthy, rosy,
graceful Fanny, with suffering and death? And what caused these
fearful evils, amongst which our tale is but one amongst ten
thousand? Lucy Neville buried her face in her hands as she sat by
the lowly pallet, where lay the faded form whence life had only half
an hour before departed, and thanked God that the temptation had
been indeed resisted, and that she had not made one at Lady
Gresham’s fête. It had not, indeed, been the primary, or even the
secondary cause. It did but strike the last blow and shiver to atoms
the last lingering dream of hope and joy which, despite of
oppression, misery, despair, will rest invisibly in the youthful heart,
till driven thence by death.

“Lucy!” exclaimed Lord Valery that same day, stopping the carriage
unexpectedly as it was about to drive off from that part of St.
James’s where it usually waited for her (she shrunk from the notice
which a nobleman’s carriage, seen in such localities as Mrs. Miller’s,
would inevitably produce),—“Lucy, an old friend wishes to recall
himself to your memory; will you give him a seat in your carriage,
and take me on the box? We both pine for fresh air, and a drive in
the Park will revive us for dinner, which, whether he will or no, I
intend this gentleman to partake.”
The words were the lightest, but the tone which spoke them
betrayed the truth at once. It was Herbert Gresham by his side.
Herbert Gresham, whose earnest eyes were fixed on hers, with an
expression in their dark depths needing no words to tell her that his
early dream, even as her own, was unchanged—that the first action
of his now unshackled will was to seek her, requiring no renewal of
acquaintance, again to love and trust her. And though the
suddenness of the meeting, the rapid transition from sorrowing
sympathy to individual joy, did so flush and pale her cheek, that her
brother looked at her with some alarm, there was neither hesitation
nor idle reserve. Her hand was extended at once, and the pressure
which clasped it was sufficient response. Whether they continued so
silent, when Herbert did spring into the carriage, and took his seat
by her side, indeed we know not. Certain it is that, had it not been
for Lord Valery, the footman might have waited long enough for
orders to drive “home;” and equally certain that no day had ever
seemed so short to Lucy,—short in its fullness of present enjoyment;
in its retrospect, could it have been but one brief day?
“And that poor girl is really gone?” inquired Lord Valery, just as
Herbert Gresham was about taking his departure, most reluctantly
warned to do so by a neighbouring clock striking midnight. “Another
victim to that hateful system, desecrating our lovely and most noble
land!”
“Dear Edward, hush!” interposed Lucy, gently, as her eye rested
on her lover.
“Do not check him, dearest, though I prize that fond thought for
me. I know the whole tale—that the fête welcoming my return, by
misdirected zeal and thoughtless folly, has added incalculably to the
general burden, and to individuals brought death and a life-long
despair. The past, alas! we cannot remedy—the future——” and his
arm was fondly thrown round Lucy, and his lip pressed her brow
—“dearest, let us hope next season there will be another Lady
Gresham’s fête fraught with happiness for all.”
The Group of Sculpture.

I.

“I have no hope in loving thee,


I only ask to love;
I brood upon my silent heart,
As on its nest the dove;

“But little have I been beloved—


Sad, silent, and alone;
And yet I feel, in loving thee,
The wide world is my own.

“Thine is the name I breathe to heaven—


Thy face is on my sleep;
I only ask that love like this
May pray for thee and weep.”
L. E. L.

“We know not love till those we love depart.”


L. E. L.

“Why will you sing that old-fashioned song, dear Annie, when you
have so many much better suited to your voice?” expostulated
Reginald de Vere, as he led the young songstress from her harp to a
more retired seat. “I do not like your throwing away so much power
and sweetness on a song which, of all others, I hate the most.”
“Do not say so, Reginald. You are not usually fastidious, or I would
say, had that sweet melody Italian words instead of English, you
would acknowledge its beauty, and feel it too.”
“Perhaps so, as it is not the melody, but the words I quarrel with
—‘Home, sweet home.’ What charm has home ever had for me?
Change the words, dear Annie, English or Italian, I care not, only
remove all association of home, and I will learn to love it more.”
“Nay, Reginald; to banish such association would be to banish its
greatest charm. One day you, too, may feel its truth.”
“Never, never!” he answered, passionately; “there is a blighting
curse around me, which it were worse than folly to resist. I must toil
on, lonely, and unblessed by one sweet tie of home—seeking for no
love, and receiving none—isolated in a world! There are many others
whose destiny is the same. Bound by the iron chain of fate, he is but
a madman who would seek to break it.”
“Destiny—fate! I thought you had long ere this banished their
baneful influence,” said Annie, in a tone of mild reproach.
“From your ear, my gentle friend, because I saw you loved not
their expression; but not from my own heart. Yet you, too, believe
all things to be pre-ordained; that not a sparrow falls to the ground
unmarked. Then, why so start at me—is not our creed the same?”
“It cannot be, Reginald. I am not wise enough to know wherein
the difference lies, I can only judge from effects; and when they are
so opposed, I fancy the cause must be so also. I do believe that all
things are ordained, but yet I am no fatalist.”
“Will you try and explain the distinction, for your words seem
somewhat contradictory.”
“I fear they do,” she replied, simply; “and I am over bold to speak
on this weighty subject at all. Your creed appears to me to consist in
this: that before your birth, your path was laid down—your destiny
fixed; that you are, in consequence, bound in chains, enclosed in
walls, from which no effort of your own will can enable you to
escape; that you must stand the bursting of the thunder-cloud—for
you have no force or energy to seek shelter, no free will to choose—
swayed by an irresistible impulse, and, consequently, not a
responsible being. Such seems to me the creed of a fatalist.”
“And you are right. Now, then, for yours; less difficult, I should
imagine, to explain, than that in which you have no interest.”
“I differ from you, Reginald. It is comparatively easy to define the
subject of a passing thought or an hour’s study; but that which we
feel, feel to our inmost soul, is not so easily clothed in words. I
believe that an eye of love is ever watching over me—a guiding arm
is ever round me; that nothing can happen to me, unless willed for
my good by my Father in heaven; but I do not believe my lot in life
marked out before I saw the light. Such a creed at once changes the
law of love into a dark and iron-bound necessity, from which my
whole soul revolts. Where would be the comfort of prayer in such a
case—the blessedness of pouring forth one’s whole soul in the hour
of affliction? for how could prayer avail us were our lot marked out?”
“And do you think prayer ever does? Do you believe that you are
answered?”
“I do, indeed, dear Reginald; not always as our own will would
dictate, but as a loving Father knows it best. I was not answered as
my heart implored when my only parent was taken from me; but I
was answered in the strength that was granted me to feel that he
was happy, and God’s will kinder and better than my own. I am not
here because it is my destiny, but because it is better for me than
the calm and quiet life I have hitherto enjoyed.”
“Your creed is indeed that of a gentle, loving woman, Annie,” said
her companion, more playfully; but he smiled not, for he knew how
chillingly a smile will fall on young enthusiasm. “But it is too
visionary, too ethereal, for cold-hearted man; perhaps not for some,
but for me there are no such dreams. My heart was once full of hope
and faith, and all things bright, and fond, and beautiful; but now
crushed, blighted, trampled on, how may it dream again? but this is
folly,” and with a strong effort he subdued emotion, and spoke more
calmly. “Let us talk of something else. You alluded but now to your
change of life, and I thought, sadly. Are you not happy?”
“I shall be in time, Reginald,” answered Annie, on whose fair
sweet face a shade had flitted at her companion’s bitter words. “All
are kind to me. My mother was Lord Ennerdale’s favourite niece, and
he loves me for her sake, and so pets me that I cannot but love him
most dearly.”
“And Lady Emily?”
“I shall learn to love as soon as she will let me. I fancy she thinks
me but a simple romantic girl and I have not courage to undeceive
her—that I can love and reverence other things besides poetry; but
it is the change of circumstances that sometimes makes me sad.
Clair Abbey is so far removed from Luscombe Cottage, that time has
not yet reconciled me to the great change.”
“Time is slow in effecting changes in you, Annie; yet ere we meet
again, trust me, you will have learned to love Clair Abbey, or
changed it for another home as high in sounding, and yet more
dear.”
“Changed it ere we meet again? What can you mean, Reginald?”
said Annie, startled yet more by his tone than by his words, but she
was not answered; for Reginald turned away directly he had spoken,
his attention called by Lord Ennerdale; and another quadrille being
formed, her hand was claimed, and she was led off almost
unconsciously—so strangely was she preoccupied—to join it.
There had been nothing in the quiet yet earnest conversation of
Reginald de Vere and Annie Grey to cause remark amongst the light-
hearted group who were that night assembled in Lord Ennerdale’s
hospitable halls. They had been intimate from childhood, and as
Annie was almost a stranger to all present, and merely regarded as a
simple country girl hardly emerged from childhood, no one was
surprised that she should prefer Reginald’s society; though there
were some young men who, attracted by the timid yet intelligent
style of her beauty, half envied De Vere the privileges of intimacy
which he so evidently enjoyed. Annie’s place seemed not amidst the
followers of fashion; the long, rich, chesnut hair owned no law but
that of nature, and flowed at will from her pale, high brow over a
neck and shoulders, whose exquisite form and whiteness were
displayed to advantage by the simple fashion of her plain black
dress; the eye so “darkly, deeply, beautifully blue,” the fair soft cheek
ever varying in colour, revealed every thought and feeling that
stirred within. The world’s lesson of concealment and reserve she
had not yet learned, for living in perfect retirement with a kind and
judicious father, of whom she was the idol, her enthusiasm had been
regulated, not chilled, and every high and poetic sentiment raised up
to and purified in the only rest for such minds—the religion of the
Bible and of Nature. Her life had passed in a small cottage on the
banks of Windermere, diversified only by occasional visits to an old
relation in Scotland; where, in fact, the first six months of her
mourning had been passed. And there, had it not been for one
cogent reason, she would have preferred remaining, as more
congenial to her taste and feelings, than the form and grandeur
which she imagined must surround the dwelling of an Earl.
Lord Ennerdale and his family had often sought to draw Sir
Edward Grey from his seclusion, anxious to notice his child; but
fearing to disturb Annie’s tranquil happiness by an introduction to a
mode of life and pleasures which her very limited fortune must
prohibit her enjoying, he had invariably declined these solicitations.
Yet when Lord Ennerdale, notwithstanding his age and infirmities,
made a rapid journey from London to Luscombe Cottage, purposely
to soothe his dying hours by the assurance that his Annie was
amply, even richly provided for, and therefore there could be no
objection to her making Clair Abbey her future home, Sir Edward
placed his weeping child in the arms of her aged uncle, and died
with a prayer for both upon his lips.
But much as Annie loved and venerated her father, it was scarcely
so much his last wish as the restlessness of her own heart, which,
even while she preferred the simple mode of living at Kelmuir, yet
reconciled her to a residence at Clair Abbey. She was restless
because her quondam playmate and chosen friend, Reginald de
Vere, was far away in his own most wretched home, with none to
sing or smile him into peace, or cautiously and gently argue away his
fits of morbid sensitiveness or overwhelming gloom. That Lord
Ennerdale not only sympathised in the young man’s causes of
depression, but loved his better qualities, admired his talents, and
regretted his failings, was sufficient to excite the warm affections of
his great-niece towards him. No spell is so powerful in opening the
heart as sympathy, with regard to the character of those we love.
Clair Abbey’s great attraction, then, to Annie Grey was, that there
she should constantly see Reginald; his concluding words, therefore,
had both startled and pained her; but she vainly waited for their
solution. She looked earnestly for Reginald to return to her; but he
was constantly engaged in apparently earnest conversation with one
or other of Lord Ennerdale’s guests. She was too guileless to believe
he shunned her merely because he failed in courage to tell her
more.
The evening closed at length; and passing along the corridor
leading from the library to the stairs, a well-known step suddenly
sounded behind her, and the voice of Reginald de Vere called her by
name.
“I thought you intended to retire without even wishing me good
night,” she said, playfully, her spirit rallying with his appearance.
“What do you mean, sir, by such treatment? Be better behaved to-
morrow, and I will be merciful, and forgive.”
“You must forgive me to-night, dearest Annie; for to-morrow will
see me many miles on my road to Portsmouth, thence speedily to
embark for Spain.”
“Portsmouth—Spain!” repeated the bewildered girl; and her hand
so trembled, that the lamp she held dropped from it, and was
instantly extinguished.
“Yes, Annie, to Spain!” he answered, struggling for calmness. “I
am of age now; poor, but not so utterly dependent as I have been.
My father’s house I will never enter more. You start, Annie, but do
not—do not condemn me. Judge me by no reasoning but that of
your own kind gentle heart. I can bear no more than that which I
have borne. Boyhood must submit to a parent’s tyranny; but
manhood owns no such law. You know how I would have loved my
father, and how he has spurned me. Still I lingered, vainly striving to
elicit one softer feeling, hoping—idiot that I was—that he would yet
love me. But the dream is over! He drew the reins still tighter, and so
snapped them; there is a measure to endurance even in a son. Do
not weep thus, Annie,” he continued, conquering his own emotion to
soothe hers, and passing his arm round her, as he had so often done
in earlier years, when as a brother he had soothed her griefs and
shared her joys. “I will not burden you with the final cause of my
present resolution. I have neither means nor influence to tread the
path to which my inmost soul aspires; and to toil for lingering years
behind a merchant’s desk or tradesman’s counter my spirit will not
bear. I have obtained a commission amongst the brave fellows now
about to join General Mina in his gallant defence of the young
queen; and with him these restless yearnings may be stilled in the
activity of martial service, or the quiet of the grave. And who will
mourn for me?” he continued, rapidly and bitterly; “who, in the wide
world, will think of me, or shed one tear for me, save thine own
sweet self? Oh, Annie, speak to me! Tell me you will think of me
sometimes. I know there will be many, very many, to supply my
place to you; but, oh, who will ever be to me as you have been?”
“And yet you have decided on this plan, endured more than ever,
and told me not a word. Reginald, was this kind?” she said,
struggling with the tears that nearly suffocated her.
“You were in grief already, Annie; how might I ask your sympathy
in mine? I know it never was refused me. I know it would not be,
even in your own sorrow; but oh, Annie, I felt if I waited to look on
you again, I should fail in courage to leave England. Yet why should
I linger? Changed as your prospects are, loved as you will be by
those so much more deserving, what could I be to you?”
“Reginald!” murmured poor Annie, wholly unconscious of the
nature of her own feelings, yet unable to utter another word.
“I know you will not forget me, Annie, dearest Annie, your nature
is too good, too kind, too truthful for such change; but, fated as I
am, how dare I ask for, hope for more than a sister’s love? Say you
will sometimes think of me, love me as—as a brother, Annie, darling!
and life will not be so wholly desolate.”
Her reply was almost inarticulate, and passionate words rose to
Reginald’s lips, but they were not spoken. He led her to the door of
her apartment without another word, wrung both her hands in his,
bade “God bless her!” and was gone. Annie stood for a few minutes
as if stunned; mechanically she loosed the wreath of white rosebuds
from her hair, the fastening of her dress, which seemed to stifle her
very breath, and then she sunk on her knees beside the bed, and
the hot tears gushed forth; and long, long she wept, as that young
guileless girl had never wept before.
Reginald de Vere was the youngest son of a private gentleman of
moderate fortune, residing in a populous city in the north of
Yorkshire. It is not necessary to dilate on feelings which Reginald’s
own words but too painfully portrayed; the “iron rule” of tyranny is
best described in the effect which it produces. The Calvinistic
principles of the elder De Vere found no softening of their natural
austerity in the acidity and moroseness of his temper; the evil had
been increased by his union with a young Spaniard—lively, frivolous,
and a Roman Catholic. How this marriage had ever come about,
nobody succeeded in discovering. Strange unions there are, but
seldom between such antipodes in character and feeling as were Mr.
and Mrs. De Vere. Their large family grew up amidst all the evils of
domestic dissension, and its subsequent misery—a father’s
unjustifiable tyranny, and a mother’s as blamable weakness. Basil de
Vere sought to instil his peculiarly stern doctrines in the minds of his
children; his wife prayed, in their hearing, that they might be saved
from such cold, comfortless belief; they shrunk from the one, and
learned no religion from the other. To shield them from the father’s
tyranny, the mother taught them deceit, lavished on them weak
indulgences, which were to be forfeited if ever revealed. Ever
witnessing and suffering the effects of dissension, what affection,
what harmony could exist between themselves? The ill effects of this
training were more discernible in some of their matured characters
than in others; some pursued an honest course, as soon as their
departure from their father’s house permitted the influence of their
better qualities, but these were mostly dwelling in foreign lands;
some had married with, some without his consent; and in his old
age Basil de Vere found himself master of a deserted hearth, with
none of his once blooming family beside him but one, and that one
was Reginald. The weak indulgence of his mother had never
softened for Reginald the tyranny of his father. She died in giving
him birth, and he had to battle through his unhappy childhood alone.
Shrinking almost in agony from his father’s voice, yearning, with all
the clinging confidence of childhood, for love, but finding none, he
turned in loathing from the continued scenes of discord which
characterised his home. He spurned with contemptuous indignation
offers of indulgence and concealment, to act as he saw others do,
and thus constantly drew upon himself the enmity of his more wily
brothers and sisters. He shrunk, in consequence, more and more
within himself, striving to keep peace with his father, but in vain; for
De Vere often raged at his children without knowing wherefore, and
the calm, dignified bearing of his youngest son would chafe him into
greater fury than palpable offence. But there were seeds of virtue,
aye, of the “nobility of genius,” in the disposition of Reginald, that
bloomed and flourished despite the unhealthy soil and blighting
atmosphere in which he moved; perhaps the kindly notice of Sir
Edward Grey assisted their development. The pale, silent, suffering
boy had appealed irresistibly to his kind heart, and for Reginald’s
sake he condescended to make acquaintance with his father.
As long as they remained in Yorkshire, Sir Edward permitted
Reginald to share much of the instruction which he himself bestowed
upon his Annie; a kindness so delicately and feelingly bestowed, that
Reginald by slow degrees permitted his whole character to display
itself to Sir Edward, and allowed himself to feel that, with so kind a
friend and so sweet a companion, he was not utterly alone. Even
when Sir Edward removed to Windermere their intercourse
continued; for there was ever a room prepared and a warm welcome
for Reginald, who turned to that cottage as a very Eden of peace
and love.
As Reginald increased in years, felt more fully his own powers,
and through Sir Edward’s friendly introductions associated with other
families, his morbid feelings did not, as the baronet had fondly
hoped, decrease, but rather strengthened, in the supposition that his
fate alone was desolate. He saw happy homes and kindly hearts; no
exertion, no effort, no sacrifice could make such his, and he believed
an iron chain of fate was round him, dooming him to misery. The
kindness of Sir Edward, of Lord Ennerdale, and others, only
deepened the vain, wild yearnings for home affections—the peace,
the confidence of home. A peculiarly fine organization of mind and
an acute perception of character caused him to shrink with pain from
general notice. The talented and gifted he admired at a distance,
feeling intuitively that such would be his chosen friends; yet, from a
sense of inferiority, refusing to come forward and permit his fine
talents to be known; at the same time shrinking from the common
herd, convinced that amongst them he should meet with neither
sympathy nor appreciation. A happy home would have been all in all
for Reginald; there the incipient stirrings of genius would have been
fostered into bloom, and the morbid feelings too often their
accompaniment regulated into peace.
The death of Sir Edward Grey and the future destination of his
daughter were, however, the final cause of his determination to
leave England. He knew it not himself; and if a light did flash upon
the darkness, it only deepened the gloom around him, by the
conviction that his doom was ever to love alone. More and more
earnestly he sought to soften his father’s temper, even to conquer
his own repugnance to the path of life his parent might assign him;
but in vain. To enumerate all the petty miseries this struggle cost
him would be impossible. The mind rises purified and spiritualized
from great sorrows; but there is no relief from the trial of an
unhappy home, no cure for the wounds of words. If domestic love
and peace be ours, we can go forth with a firm heart and serene
mind to meet the trials of the world; alas! alas! for those who have
no such haven, no such stay!
Never did Reginald De Vere make a greater mistake than in the
supposition that a military life would bring him the happiness for
which his parched soul so thirsted. He could not associate the
favourite pastime of his childhood, carving in wood, stone, or
whatever material came first to hand, with the feverish yearning for
exertion and excitement, which possessed his whole being. He could
not feel that the one sprang from the other, or rather that the power
which urged the former was secretly working in his mind, and
causing an utter distaste for all mechanical employment. He was too
unhappy to examine the source of his restlessness, and knew no one
who could explain it for him.
Lord Ennerdale and his sons were all men of worth and talent, and
firm encouragers of art and literature; but not themselves children of
genius, they failed in the subtle penetration which could discover its
embryo existence. Had Sir Edward lived he would have seen further;
but still all his friends had dissuaded Reginald from entering on a
military career, but he was firm; and in less than a week after his
agitated parting with Annie, a fair wind was rapidly bearing him to
the shores of Spain.
Days and weeks passed, and Annie Grey sought with persevering
effort to regain her former calm and happy temperament; and she
succeeded so far as to conceal from her relatives the secret of her
heart. The agony of that parting moment had transformed her, as by
some incomprehensible spell, from the child to the woman; and so
sudden had been the transition, that she felt for days a stranger to
herself. Reginald had always been dear to her, but she knew not,
imagined not how dear, until that never-to-be-forgotten evening; his
words returned to her again and again, and sad, desponding as they
were, she would not have lost one of them. She who had been so
constantly active, flitting like a spirit from one favourite employment
to another, now seemed to live but on one feeling; but her mind was
too well regulated to permit its unrestrained indulgence. Young as
she was, dependent on herself alone for guidance in this new and
absorbing state of being, thrown in quite a new position for luxury
and wealth, as a cherished member of her uncle’s family, yet her
character, instead of deteriorating, matured, uniting all the outward
playfulness of the child with the inward graces of the woman.
Lord Ennerdale’s domestic circle formed a happy contrast to that
of the ascetic Basil De Vere. His children were all married except his
eldest son, Lord St. Clair, and eldest daughter, Lady Emily; but the
ties of family had never been broken, and happy youth and blooming
childhood were almost always round the earl. With all these Annie
was speedily a favourite; and easily susceptible of kindness and
affection, Clair Abbey soon became endeared to her as home.
By a strange contradiction, Annie’s interest and affection were,
however, excited the strongest towards the only member of Lord
Ennerdale’s family who retained reserve towards her. What there
was in Lady Emily St. Clair to attract a young and lively girl, Annie
herself might have found it difficult to define; for not only her
appearance, but her manners were against her. Stiff, cold, even
severe, she usually appeared; and when she would at times relax,
and seem about to enter with warmth and kindness into Annie’s
studies or pursuits, she would suddenly relapse into coldness and
reserve. Sometimes, when eagerly conversing with Lord St. Clair, on
the exquisite beauty of nature, or of some favourite poem, when the
spirit of poetry breathed alike from her eyes and from her lips, Annie
would catch the eye of Lady Emily fixed upon her sadly and
pityingly; or if she smiled, the smile was peculiar, it might be even
satirical; yet she was never satirical in words, nor did it seem in
character—too feelingly alive to the dictates of kindness ever
willingly to inflict a wound. To discover her real character was
difficult; Annie judged more by her habits than her words. Lady
Emily never said that her love of flowers amounted to a passion, that
to have them around her in their freshness, to seek them alike from
the garden and the wild, to collect, dry, and arrange them in such
tasteful groups and such brilliancy of colouring, that the choicest
paintings looked dim beside them, was her favourite pleasure, but
Annie was ever ready with some newly discovered plant, or the moss
and weed she needed—ever the first to remove the dying buds, and
supply their place around her boudoir with the freshest and fairest
she could select. Lady Emily never spoke of poetry, never
acknowledged that she could either admire or enter into it; but there
were extracts in her writing, attached sometimes to drawings,
sometimes to her books of flowers, that betrayed such a refinement
of taste, and acute perception of the pure, the beautiful, and the
spiritual, in nature and in man, that Annie suspected she was herself
a poet; but yet how could she reconcile the unimpassioned coldness
of her usual mood with the light and life of poetry? Yet though fairly
puzzled, Annie so judiciously assisted her researches, that Lady
Emily often wondered how a mark could come so exactly in the
place she wished, when the thought, for whose echo she looked,
had been breathed to none; but even had these attentions escaped
her notice, it must indeed have been an icy heart to withstand the
sweetness of Annie’s manner; whenever her cousin’s mood was
irritable, her temper somewhat ruffled, there seemed a magic
around Annie not only to bear with irritation, but to reconcile the
subject of that irritation to herself and all around her; and when so
languid and weak as really to be ill, though she would never allow it,
who so active as Annie to prevent all annoyance to the invalid, or
interfere with the only pursuits she could enjoy? Yet no show of
affection acknowledged these attentions; but by very slow degrees
the Miss Grey changed into Anne, and finally into the pretty
denomination by which she was always addressed; and the smile
and tone with which she spoke to her, satisfied the orphan that she
had not worked in vain.
Even if Annie’s conduct had failed to rivet the notice of Lady Emily,
it had gained for her the interest and sincere affection of another.
Lord St. Clair was devotedly attached to his sister, and all who had
the good sense to appreciate her were sure to obtain his esteem;
then in the prime of life, he foresaw no danger in his intimate
association with and admiration of his young cousin, a girl but just
seventeen; and it was a pleasure to him to draw her out, and repay
by every kindness on his part her attention to his sister. A
disappointment when very young had caused him to remain single.
“I do not say I shall never marry,” he often said, in answer to his
father’s solicitations on the subject; “for then I should consider
myself bound not to do so, however my heart might dictate; but it is
unlikely.”
Annie Grey had not, however, been domiciled many months in
Clair Abbey, before Lord St. Clair’s sentiments on this subject
underwent some change.
From the time of Reginald’s departure the public journals became
suddenly endowed with an interest to Annie, equal to that of the
most ardent politician. The disturbed state of Spain, the constant
marchings and counter-marchings of General Mina’s army, prevented
any regular communication from Reginald; once or twice she had
heard from him direct, and treasured indeed were those letters,
honourably as the young man kept to his resolution, never by one
word to draw Annie into an engagement, or even an avowal that she
returned his love. In the papers she often read his name among the
bravest and most daring of the British soldiers. One anecdote,
officially reported and communicated to Lord Ennerdale, afforded her
still dearer food for fancy. The service in which he was engaged was
exposed to all the horrors of civil warfare; slaughter and desolation
followed in the train of both armies. Young De Vere, at the head of a
picked band, had thrown himself in the very midst of a mêlée,
determined on saving the unoffending women and children, and
aged peasants of the opposing party, all of whom were about to be
sacrificed to the misguided rage of the royal troops; the village was
in flames, and the peasants, neutral before, swore to be avenged.
The exertions of the young Englishman, however, worked on both
parties; he calmed the excited spirits of his own men, and promised
protection and safety to the oppressed. One group particularly
attracted him; a young mother, clasping an infant tightly to her
breast, and two fine boys, twining their arms round her, as to protect
her with their own lives. Reginald did not know that it was her infant
he had saved from a brutal death, but his look was arrested by the
intense feeling glistening in her large dark eyes, and by the impotent
passion of her eldest boy, who, clenching a huge stick, vowed he
would join his father, who was a Carlist soldier, and revenge the
insults offered to his mother. De Vere jestingly laid his hand on the
stripling’s shoulder, declaring he was a young rebel and his prisoner.
The agonized scream of the poor mother changing on the instant
into the wildest accents of gratitude, as she recognised in Reginald
her baby’s preserver, and to the earnest supplication that he would
send them on in safety, removed all feelings of mere jest. Reginald
soothed her fears, and selecting a guard of his own countrymen, on
whom he could depend, sent her and her children under their care
to the outposts of the Carlist camp. General Mina smiled sadly when
this anecdote was told him. “The age of chivalry is over, my young
friend,” he said, mournfully. “Your act was kind and generous, but I
fear of little service. The Carlists are not likely to check their career
of devastating warfare because we have spared one insignificant
village; nor will you have any demand upon their favour should you
unfortunately fall into their hands.”
“Chivalry and its romance may be over,” thought Annie, as again
and again her mind reverted to its one fond theme. “But my father
once told me ‘a deed can never die;’ and, even if indeed it were to
do no good, surely his motives will meet with the appreciation and
admiration they deserve; there must be some among the good and
noble to do him justice.”
How the young heart revels in every proof, however trifling, on the
worth of him it loves. The restlessness of a scarcely acknowledged
passion merged into a species of glowing happiness, the basis of
which Annie might have found it difficult to define. In its indulgence
she forgot the distance between them, the darkening aspect of his
future, the despondency breathing in his last farewell—forgot all but
the passionate words, “Who will be to me as you have been?” And
what will so elevate the character and purify the heart, and shed
such sweet rosy flowers over every thought, and act, and feeling, as
the first fresh feelings of all-hoping, all-believing love? Annie’s
beauty, matured beneath the magic of such dreams, excited
universal admiration; but the young girl knew it not.
“No breakfast for loiterers!” exclaimed Lord St. Clair, playfully
holding up his hand, as Annie sprang through an open French
window into the breakfast-room one lovely summer morning, her
cottage bonnet thrown back, her luxuriant hair somewhat
disordered, her cheek and eye bright with health and animation, and
laughing gaily at Lord St. Clair’s threat.
“Here has Emily been looking starch and prim for the last half-
hour, thinking unutterable things of the folly and romance which can
be the only reason of young ladies’ early wanderings in the lonely
districts about Keswick Lake. Ah, you little fox, prepared with a bribe
to ward off the weight of her displeasure,” he said, as Annie laid the
fruit of her researches, a rare and exquisite plant, on the table by
her cousin, and Lady Emily half smiled.
“And there’s my father in a complete fever fearing that his
blooming little niece had been carried off, or eaten up by one of the
wild men or monsters of the mountains, and threatening to search
for her himself, directly after breakfast.”
“Thank you, my dear, kind uncle,” replied Annie, gaily, bending
over Lord Ennerdale to kiss his forehead. “Never be anxious about
me. I have suffered no further inconvenience than extreme hunger,
which I satisfied at Nanny’s cottage, by a slice of her brown bread
and a cup of warm milk. No romance in that, Lord St. Clair, at least.”
“A fortunate occurrence for you, as it may save you from a lecture
on the impropriety of indulging love-lorn dreams in solitude. Why,
Annie, you are actually blushing; if it were not an utter impossibility
for romantic young ladies to feel hungry, I should say your very
looks pleaded guilty. Look at her, Emily—you had better begin.”
“No, I thank you, Henry; I never give lectures, even when
deserved, in public,” was his sister’s quiet reply.
“Well, the offence brings with it its own punishment, for here
come the contents of the postman’s bag, and so a truce to our sage
converse; and you, Miss Annie, must eat your breakfast in meditative
silence.”
“Or in perusing what she likes better. Here, my little politician;
your eyes are pleading, though your lips are silent,” said Lord
Ennerdale, gaily throwing to her a packet of newspapers without
opening them.
“You are much too young to be a politician; besides, I hate
women to dabble in politics, so give me a better reason for being the
first reader of all the papers, or you shall not have them,” interposed
Lord St. Clair, keeping firm hold of the packet, which he had caught.
“On my honour, I never read a word of politics,” replied Annie, half
playfully, half eagerly, but blushing deeply as she met Lord St. Clair’s
penetrative glance. He relinquished them with a half sigh, and bent
over his despatches. Silence ensued for several minutes, each
seemingly engrossed with his occupation. Lady Emily was the first to
move, and after carefully sorting and arranging the flowers Annie
had brought her, was about to leave the room.
“Annie, my dear child! what is the matter?” she exclaimed, in a
tone which electrified her father and brother, so utterly was it unlike
her usually measured accents; and startled out of all stiffness and
dignity, she was at the poor girl’s side in an instant. Annie’s cheek,
lips, and brow were cold and colourless as marble, and there was
such rigid agony imprinted on every feature, that Lady Emily well-
nigh shuddered as she gazed. “Speak to me, Annie, love! What is it?
Try and speak, dearest; do not look at me with such a gaze,” she
continued, as Annie slowly raised her eyes, which were bloodshot
and distended, and fixed them on her face; she evidently tried to
speak, but only a gasping cry escaped, and that terrible agony was
lost for a time in an unconsciousness so deep that it almost seemed
of death.
Lord St. Clair stood paralysed, but then he snatched up the fatal
paper, and one glance sufficed to tell him all, all that he had
suspected, all that for his own happiness he had feared; but he
could only think of Annie then, and perceiving how ineffectual were
all the usual efforts to restore animation, he threw himself on
horseback, and never rested till he had found and dragged back with
him the medical attendant of the family, whose skill was finally
successful. Annie woke from that blessed relief of insensibility to a
consciousness of such fearful suffering, that as she lay in the perfect
stillness enjoined by the physician, she felt as if her brain must reel,
and fail beneath it. It was not alone the death of him she loved, that
the idol of her young affections was lost to her for ever, but it was
the horrid nature of his fate which had so appalled her. In the gallant
defence of a royal fort he had been left almost alone, all his
companions falling around him; severely wounded, and overpowered
by numbers, he was taken by the Carlists, dragged to their camp,
and twenty-four hours afterwards shot, with other ill-fated men,
literally murdered in cold blood. Three times Annie’s eyes had glared
on the paragraph, reading again and again the list of the
unfortunate men who had thus perished, as if Reginald’s name could
not be amongst them; alas! it was there, pre-eminent, from the
courage, the youth, and the official rank of the bearer. And in that
dreadful stillness the whole scene rose before her, vivid as reality—
ghastly figures flitted before her; and then she saw Reginald as they
parted; and then full of life and excitement in the field; and then
covered with blood and wounds. She seemed to see him bound and
kneeling for the fatal stroke, and the shot rung in her ears, clear,
sharp, and strangely loud, till she could have shrieked from the
bewildering agony: she tried to banish the vision, to escape its
influence, but it gained strength, and force, and colouring, and
before midnight Lady Emily watched in grief and awe beside the
couch where her young cousin lay, and raved in the fearful delirium
of a brain fever.
Many weeks elapsed ere Annie could again take her place
amongst her family; alternate fever and exhaustion had so
prostrated her that her life was more than once despaired of. Had
she been aware who it was so constantly and gently tended her,
teaching her voice to forget its coldness, her manners its reserve, to

You might also like