3. Compile-Time DSP: Filters, Tables and Constellations¶
Look at how filter taps come into existence in PySDR. The Filters chapter calls scipy.signal.firwin(101, cutoff, fs=sample_rate), the Synchronization chapter builds a fractional delay filter from np.sinc and np.hamming, and the Pulse Shaping chapter writes out the raised-cosine formula. Every time the script runs, the taps are computed again, from parameters that never change while the program runs.
In a deployed C++ receiver you have three options for such numbers. You can compute them in Python once and paste a list of 101 floats into the source code, which works until someone changes the cutoff frequency and forgets to regenerate them, and which leaves a block of numbers nobody can review. You can compute them at start-up, which means carrying a design library into the product and running it before the first sample is processed. Or you can let the compiler compute them: the source code says “a 101-tap low-pass at 100 kHz for 1 MHz”, and the program contains the 101 numbers. This chapter is about the third option, which modern C++ makes surprisingly pleasant, and about a bonus that comes with it: the compiler can also check the result.
constexpr: One Function, Two Times¶
A function marked constexpr may be evaluated by the compiler when it is called in a context that requires a constant, and it runs normally at run time otherwise. It is the same function either way. Here is the window-method low-pass design, the algorithm behind scipy.signal.firwin with its default Hamming window, written as a constexpr function (code/include/cppsdr/design.hpp):
template <std::size_t N>
constexpr std::array<float, N> lowpass(double cutoff, double fs) // firwin(N, cutoff, fs=fs)
{
static_assert(N % 2 == 1, "use an odd number of taps (type I linear phase)");
const double c = cutoff / (fs / 2); // cutoff relative to Nyquist
const auto w = hamming<N>();
std::array<double, N> h{};
double sum = 0;
for (std::size_t n = 0; n < N; ++n) {
const double m = double(n) - double(N - 1) / 2;
h[n] = c * cx::sinc(c * m) * w[n];
sum += h[n];
}
std::array<float, N> out{};
for (std::size_t n = 0; n < N; ++n) out[n] = float(h[n] / sum); // unity gain at DC
return out;
}
Two design decisions are visible in the signature. The number of taps is a template parameter, so it is part of the type: the result is a std::array<float, 101>, a fixed-size value that needs no heap and knows its own length. And the static_assert turns PySDR’s advice “it is recommended to use an odd number of taps” into a rule the compiler enforces.
Using it looks like this:
constexpr auto taps = design::lowpass<101>(100e3, 1e6); // computed while compiling
Because taps is declared constexpr, the compiler must evaluate the call. The result agrees with scipy.signal.firwin(101, 100e3, fs=1e6) to within \(7 \cdot 10^{-9}\), which is float rounding (code/tests/test_design.cpp checks this against a file written by SciPy).
Is the design code really gone from the program? We compiled a small program that prints one of the taps and looked at it with nm: there is no sin, no cos and no design function in the binary, and the 101 coefficients sit in the read-only data section (__TEXT,__const on macOS, .rodata on Linux). On a microcontroller that is flash memory; on an FPGA soft core or a Zynq it is part of the image that gets loaded. Nothing runs at start-up.
Two related keywords complete the picture. consteval marks a function that may only run at compile time, useful for table generators that should never accidentally end up in the hot path. constinit on a variable guarantees that it is initialized at compile time without making it constant, which avoids the static initialization order problems that Kormanyos discusses in Real-Time C++ (4th ed., chapter 8).
The Missing Piece: a constexpr sin()¶
There is a catch. The design needs \(\sin\), \(\cos\) and friends, and std::sin is not constexpr before C++26. The paper that changes this, P1383R2 “More constexpr for <cmath> and <complex>” (wg21.link/p1383), was voted into the C++26 working draft in 2023, but standard libraries are still catching up. GCC already accepts constexpr double a = std::sin(0.5); as an extension; Clang 21 with libc++ rejects it, even in -std=c++2c mode.
So for portable code today we write a few functions ourselves (code/include/cppsdr/cx_math.hpp). They do not need to be fast, only accurate, because they run inside the compiler. The sine reduces its argument to \([-\pi/4, \pi/4]\) and sums a short Taylor series:
constexpr double sin(double x)
{
const double q = round(x / (pi / 2)); // nearest multiple of pi/2
const double r = x - q * (pi / 2); // r in [-pi/4, pi/4]
switch (((std::int64_t(q) % 4) + 4) % 4) {
case 0: return detail::sin_poly(r);
case 1: return detail::cos_poly(r);
case 2: return -detail::sin_poly(r);
default: return -detail::cos_poly(r);
}
}
exp and log use the same idea (reduce to a small interval, sum a series, scale back), and sqrt is Newton’s method. All of them agree with <cmath> to within a few units in the last place over the ranges filter design needs, which the test checks. When your standard library implements P1383, you can delete the file.
Letting the Compiler Check the Design¶
Once the taps are a compile-time constant, any property you can compute about them can be checked with static_assert. A failing check stops the build, so a wrong filter never becomes a program:
constexpr auto lp = design::lowpass<101>(100e3, 1e6);
static_assert(design::is_symmetric(lp), "linear phase needs symmetric taps");
static_assert(cx::abs(design::dc_gain(lp) - 1) < 1e-6, "unity gain at DC");
static_assert(design::to_db(design::gain_at(lp, 200e3, 1e6)) < -50, "stopband at 200 kHz");
The last line evaluates the frequency response at 200 kHz (a 101-term DFT, computed by the compiler) and insists on at least 50 dB of attenuation. These are the checks you would otherwise do by looking at a plot in PySDR’s style, written down as part of the code, and re-checked on every build when someone changes a parameter.
The same works for the fractional delay filter from the Synchronization chapter, which mirrors PySDR’s four lines of NumPy:
constexpr auto fd = design::fractional_delay<21>(0.4); // 0.4 samples, as in PySDR
static_assert(!design::is_symmetric(fd), "a fractional delay is not symmetric");
and for the band-pass example from PySDR’s Filters chapter, firwin(101, [100e3, 200e3], pass_zero=False, fs=1e6):
constexpr auto bp = design::bandpass<101>(100e3, 200e3, 1e6);
static_assert(cx::abs(design::gain_at(bp, 150e3, 1e6) - 1) < 1e-6, "unity gain mid-band");
static_assert(design::gain_at(bp, 0, 1e6) < 0.01, "no DC");
The Compiler Can Even Run the Filter¶
A constexpr function may use loops, local variables, std::array and (since C++20) the arithmetic of std::complex. That is enough to run a whole streaming filter inside the compiler. fir_static in fir.hpp is a small FIR filter whose size comes from its taps, with a mirrored delay line (see FIR Filters in C++) stored inside the object:
template <std::size_t N>
class fir_static {
public:
constexpr explicit fir_static(std::array<float, N> const& h) : h_(h) {}
constexpr cf32 step(cf32 x) { /* write x twice, dot product over the window */ }
...
private:
std::array<float, N> h_;
std::array<cf32, 2 * N> z_{};
std::size_t pos_ = 0;
};
consteval bool impulse_returns_taps()
{
fir_static f{taps}; // N = 101 deduced from the std::array
for (std::size_t n = 0; n < taps.size(); ++n)
if (f.step(n == 0 ? 1.0f : 0.0f) != cf32(taps[n], 0)) return false;
return true;
}
static_assert(impulse_returns_taps(), "the compiler ran the filter");
fir_static f{taps} uses class template argument deduction: the compiler reads \(N = 101\) off the array type, so the filter’s size cannot disagree with its taps. The static_assert then feeds an impulse through the filter and checks that the taps come out, the textbook definition of an FIR filter’s impulse response, as a unit test that runs before the program exists. This compiles with both Clang 21 and GCC 16.
A 0/0 in the Raised Cosine¶
The raised-cosine pulse from PySDR’s Pulse Shaping chapter is
and its denominator is zero at \(t = \pm T_s / (2\beta)\). At exactly those points the cosine in the numerator is \(\cos(\pi/2) = 0\) too, so the formula reads \(0/0\); the actual value is the limit
which reads: at the problem points, the pulse is \(\pi/4\) times the sinc evaluated at \(1/(2\beta)\) (the standard result, see for example the raised-cosine filter article). Whether the problem points fall on a tap depends on \(\beta\) and the samples per symbol. With PySDR’s \(\beta = 0.35\) and 8 samples per symbol they do not (\(T_s/(2\beta) = 11.4\)), so the main example is fine. Its OQPSK/eye-diagram example guards against it by adding 1e-20 to the denominator. That avoids the division by zero, but not the problem: the numerator is not exactly zero in floating point (np.cos(np.pi/2) is \(6 \cdot 10^{-17}\)), so the “fixed” tap becomes \(6 \cdot 10^{-17} / 10^{-20}\), a number in the hundreds. In that example, changing beta = 0.35 to beta = 0.2 (with its 32 samples per symbol) produces a tap of 780 at \(t = -2.5\) symbols, where the correct maximum of the pulse is 1.
The C++ design handles the point explicitly with the limit:
constexpr double raised_cosine_at(double t, double Ts, double beta)
{
const double x = 2 * beta * t / Ts;
if (cx::abs(cx::abs(x) - 1) < 1e-12) return cx::pi / 4 * cx::sinc(1 / (2 * beta));
return cx::sinc(t / Ts) * cx::cos(cx::pi * beta * t / Ts) / (1 - x * x);
}
and the test pins it down for a case that hits the singular tap (\(\beta = 0.3\), 6 samples per symbol, singular at \(t = 10\)):
constexpr auto rc = design::raised_cosine<103>(0.3, 6);
static_assert(cx::abs(rc[51] - 1.0f) < 1e-6f, "peak at t = 0");
static_assert(cx::abs(rc[51 + 10] - (-0.12990381f)) < 1e-6f, "exact limit at the singular point");
The point is not that Python could not do the same; it could. The point is where the check lives. A design function that runs at compile time invites you to write down what a correct result looks like, and then every parameter change is checked by the build.
Tables: Sine Waves and Constellations¶
Filters are not the only constants in a receiver.
The integer-phase oscillator from Oscillators and Frequency Shifting needs a table of 1024 sine segments. It is now built by the compiler, and the table size is checked to be a power of two, because the oscillator selects entries with the top bits of the phase:
template <std::size_t N>
constexpr std::array<sine_segment, N> sine_table()
{
static_assert(std::has_single_bit(N), "table size must be a power of two");
...
}
static constexpr auto table_ = design::sine_table<1024>(); // inside nco_fixed_lut
PySDR’s Digital Modulation chapter creates QPSK symbols by computing angles at run time. In a modem, the constellation is a lookup table indexed by the bits, and it should be Gray coded: neighbouring points differ in exactly one bit, so that the most likely symbol error costs only one bit error. The Gray code of \(k\) is simply k ^ (k >> 1), so a PSK table is a few lines:
template <std::size_t M>
constexpr std::array<std::complex<float>, M> psk(double phase0 = 0)
{
static_assert(std::has_single_bit(M), "M must be a power of two");
std::array<std::complex<float>, M> table{};
for (unsigned k = 0; k < M; ++k) { // k-th point around the circle gets label gray(k)
const double a = phase0 + 2 * cx::pi * k / double(M);
table[gray(k)] = {float(cx::cos(a)), float(cx::sin(a))};
}
return table;
}
constexpr auto qpsk = design::psk<4>(cx::pi / 4); // PySDR's 45, 135, 225, 315 degrees
constexpr auto qam64 = design::qam<64>(); // square QAM, unit average power
static_assert(design::is_gray_coded(qpsk) && design::is_gray_coded(qam64));
is_gray_coded finds every symbol’s nearest neighbours and checks with std::popcount(a ^ b) == 1 (from <bit>, C++20) that their labels differ in one bit. Mapping bits to symbols at run time is then one array access, qpsk[bits]. The Gray property of a 64-QAM table is exactly the kind of thing that is easy to get subtly wrong by hand and tedious to check by eye; here the compiler checks it on every build.
The same tables in VHDL. FPGA designs need the same constants: filter coefficients for a FIR core, sine ROMs for a DDS, constellation tables for a mapper. They are usually generated by a script and pasted into a VHDL package. With the design functions in C++, a ten-line program can print them as a VHDL constant ... : coeff_array := (...) (in the fixed-point format of the hardware), from the same source that the C++ model uses. The bit-true model and the hardware then cannot drift apart. This is the subject of a later chapter on fixed point.
Key Takeaways¶
Put the design parameters in the source and let
constexprfunctions compute the numbers: no pasted coefficient lists, no design code or start-up work in the product. The same function also runs at run time when the parameters are not known in advance.Make sizes template parameters (
std::array<float, N>), so that the size is part of the type and class template argument deduction carries it along.Write down what “correct” means with
static_assert: symmetry, DC gain, stopband attenuation, an impulse test, the Gray property. The compiler re-checks it on every build.std::sinbecomesconstexprin C++26 (P1383). Until your library has it, a small hand-writtenconstexprmath header does the job.Watch the edge cases a formula hides: the raised cosine has a \(0/0\) point that an
+1e-20cannot fix, but an explicit limit can.