Real-Time C++: Efficient Object-Oriented and Template Microcontroller Programming Christopher Kormanyos instant download
Real-Time C++: Efficient Object-Oriented and Template Microcontroller Programming Christopher Kormanyos instant download
https://ebookmeta.com/product/real-time-c-efficient-object-
oriented-and-template-microcontroller-programming-christopher-
kormanyos/
https://ebookmeta.com/product/object-oriented-programming-with-
swift-2-1st-edition-gaston-c-hillar/
https://ebookmeta.com/product/object-oriented-programming-first-
edition-m-a-ansari/
https://ebookmeta.com/product/python-3-object-oriented-
programming-building-robust-and-maintainable-software-with-
object-oriented-design-patterns-in-python-2nd-edition-phillips/
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/
https://ebookmeta.com/product/bound-to-the-cowboy-a-small-town-
off-limits-romance-farrah-jane/
https://ebookmeta.com/product/ukraine-and-russia-from-civilized-
divorce-to-uncivil-war-1st-edition-paul-danieri/
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
© 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.
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
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 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.
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
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
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 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
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.
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
Companion Code
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>
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>
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.
xxi
xxii Preface to the First Edition
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
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,
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.
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 .
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
#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;
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();
protected:
communication();
private:
bool recv_ready;
std::uint8_t recv_buffer;
};
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.
xxix
xxx Contents
Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Acronyms
xxxvii
xxxviii Acronyms
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
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.
// chapter01_01-001_led_program.cpp
#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;
*reinterpret_cast<volatile bval_type*>(pdir)
|= bval;
}
1.1 The LED Program 5
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.
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].
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);
*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++
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,
The corresponding implementation details of the led class could be put in the
led.cpp source file. For example,
1.3 Class Types 9
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);
*reinterpret_cast<volatile bval_type*>(pdir)
|= 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,
“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.
“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