CMake presets and C++23 in a real codebase, our C++ MMORPG. Each way the game is built, release, AddressSanitizer, ThreadSanitizer, the fuzzers, clang-tidy, coverage and profiling, gets a configure, build and test preset with its own build folder, and a workflow preset runs a whole sanitizer build in one command, in Docker and in CI too. Then the game moves to C++23: deducing this lets the server's timer lambdas hand their own object to Asio without std::function, once a concept that checks its own answer is out of the way and the sanitizers move from Clang 18, which crashes on them, to Clang 21, and the terrain's grids read as grid[j, i]. std::mdspan builds on the Mac and not with GCC 15, so the grid becomes our own class, with a check on each index that AddressSanitizer can't make, and the doctor script asks the compiler for the parts of C++23 we use. This is episode 73 of a series about building an MMORPG from scratch in C++, with the focus on the engineering around the game.
The code
Each step on screen is a tag in the game's repository. The code at the end of the episode is ep073/end.
- 2:23
ep073/step-1CMake presetsBrowseChanges - 5:33
ep073/step-2Building and testingBrowseChanges - 8:05
ep073/step-3Presets in Docker and CIBrowseChanges - 10:33
ep073/step-4C++23BrowseChanges - 11:37
ep073/step-5A lambda that waits againBrowseChanges - 13:41
ep073/step-6A lambda that waits againBrowseChanges - 15:09
ep073/step-7A lambda that waits againBrowseChanges - 16:01
ep073/step-8Grids by row and columnBrowseChanges - 19:38
ep073/step-9Grids by row and columnBrowseChanges - 22:15
ep073/step-10Checking the compilerBrowseChanges - 24:18
ep073/endThe docsBrowseChanges
Transcript
Intro
0:00 Welcome back to episode seventy-three, where we're going to give each way the game is built a name, with CMake presets, and then move the code to C++23. A couple of its newer features tidy up code we've had for a while. The compilers trip us up three times on the way, once on the Mac and twice in Docker, with CI's compilers. First, a quick look at what we'll have by the end.
0:25 Each build the game has, from the one that ships to the sanitizers, the fuzzers and coverage, is a preset with a name, and a workflow preset configures, builds and tests one of them in a single command.
0:36 The code is on GitHub, as open source, and linked from the series' website, where each episode has a page with its code at each of its steps.
Last time
0:44 A quick reminder of where we left off. Last time, we wrote a red-team client, a player without a window that breaks the client's rules one at a time and prints what it gets for it. The server already stopped most of what it tried, from more inputs than ticks to a swing from twenty metres away. Putting the sword in the bag as each blow landed got about twice the hits, though, so a skill now keeps the timings of the weapon it started with. And decision record twenty-five says why the server checks what a client asks for.
Today
1:13 Today, the game is built seven ways, starting with the release build the servers ship as. There's one with the address and undefined behaviour sanitizers and one with the thread sanitizer, one for the fuzzers, one for the compile commands clang-tidy reads, one for coverage, and a profiling build further down. Each of them is a cmake line with its flags spelled out, in a stage of the Dockerfile, and again in the docs. And on your machine, they all share the build folder, so going from a sanitizer build back to the release one compiles everything again.
1:47 So, we're going to give each of them a name, in CMake presets, where a single command configures a build, builds it and runs the tests. Then we move to C++23, the standard after C++20, which our compilers have most of by now. It lets the server's timers hand their own lambda back to the timer without a std function in between, and lets us read our grids by row and column. And last, the doctor script asks your compiler for the parts of C++23 we use. So, let's get going, with the first of those presets.
CMake presets
2:23 CMake reads presets from a file at the top of the repo, CMake presets dot json, where each preset gives a name to settings we'd otherwise type on the command line. Version six of its format is the one that has workflows, which we'll get to, and the file asks for CMake three point twenty-eight, as the game does. A configure preset says how a build folder gets configured: the generator, the folder, and the cache variables we used to pass with dash D. The first is release, the build the servers and the client ship as, and its display name is what CMake prints next to it when we list them. It generates for Ninja, as our builds have from the start, into the build folder, so the scripts, the Dockerfile and the docs that run build slash bin carry on working. Its one cache variable is the build type. Next comes a preset that isn't used on its own, so it's hidden: CMake doesn't list it, and other presets inherit from it. Each preset that inherits it builds into a folder named after it, build dash asan, say, so a sanitizer build and the release one keep their objects apart, and going between them rebuilds nothing. It also picks Clang, for C and for C++, as libFuzzer and the coverage counters are Clang's, and our sanitizer builds have used Clang since episode twenty-eight. Then comes asan, short for AddressSanitizer, which inherits from the hidden preset, with its compilers and its folder, optimised but with debug information, as a sanitizer's report names the lines, and with the address and undefined behaviour sanitizers. tsan inherits from the hidden preset as well, with RelWithDebInfo too, and differs in its sanitizer, the thread one, which looks for data races, and which can't go into a build with the address one. The fuzz preset inherits from asan, as the fuzzers run with those sanitizers on, and turns the fuzzers on. The tidy preset configures with the fuzzers too, so their files are in the compile commands clang-tidy reads, and nothing it builds is ever run. Coverage turns on Clang's counters, which count how often each line runs as the tests go, and leaves the build type empty, so the optimiser doesn't fold lines away from under the counts. Last, profile inherits from release, so it's optimised the way the servers ship, with Tracy's zones compiled in. It needs a folder of its own, as inheriting release would have put it in the build folder, on top of the release objects. Git ignores the new build folders, and CMake user presets, a file where you can keep presets of your own, one for another compiler, say, without committing them. Docker leaves the build folders out of what it copies, as CMake refuses a build folder that was configured somewhere else. And the game's version goes up to zero point seventy-three point zero.
5:08 Let's see what CMake makes of it, in a terminal at the top of the repo. List presets prints each configure preset with its display name, and the hidden one isn't there. Dash dash preset asan configures the sanitizer build. CMake fetches the libraries, as it does for any new build folder, and finds Apple's Clang, which is what clang means on a Mac, and it writes the build files into build dash asan.
Building and testing
5:34 Configuring is a third of the work, so the rest of the file names how each build is built, and how its tests run. A build preset points at a configure preset, and can name the targets to build, or leave them out, to build them all. For release and the two sanitizers, that's all a build preset needs: each builds the whole game, in the folder its configure preset names. The fuzz preset builds the two fuzzers and nothing more, as the fuzz stage runs those and nothing else. Tidy builds the libraries whose headers protoc writes, as clang-tidy reads those headers along with our code, and they don't exist until protoc has run. Coverage builds everything, so each program can count its lines, and profile builds the world server, the program Tracy profiles. A test preset runs ctest in a configure preset's folder, with the options we'd otherwise type after it. A hidden one holds what they have in common: the output of each test that fails, which we used to ask for with dash dash output on failure. The release and asan ones take it as their parent and name their configure preset. The thread sanitizer's preset sets an environment variable as well. It points the thread sanitizer at our suppressions file, for what Mesa does with its threads in Docker. And the coverage preset sets one of its own, so the coverage tests write their counts into their build folder. There's a file for each test's process, named by its process id, which the coverage script is going to merge once they're done. A workflow preset runs steps in order, a configure preset, a build preset and a test preset, starting with release. It holds a list, where each entry names its kind and a preset of that kind, so the release workflow names the release presets we just wrote, one of each, in the order they run. With one for asan, a whole sanitizer run is one command. I think this is the part I'd have liked back in episode twenty-eight, when the sanitizers came in, and their flags went into five places. And there's one for the thread sanitizer, which runs its tests with the suppressions in place.
7:39 So, let's run the asan workflow, which the sanitize stage in Docker is going to run too. It configures its folder, builds the libraries and the game with the sanitizers, which takes a while on the Mac, and then runs the tests, the client's too, which open their windows on the Mac as they go. Grep keeps the line that sums them up. They all pass, with the address and undefined behaviour sanitizers built into each of them.
Presets in Docker and CI
8:06 Now the Dockerfile can use them, a stage at a time, from the top. The build stage configures with the release preset and builds with it, and the test stage runs the release test preset, under xvfb run, which gives the client's tests a screen to draw on. The sanitize stage takes the name of a preset as its build argument, asan unless we say otherwise, and we note that a workflow preset configures, builds and runs the tests. Its thread sanitizer setting stays, for the servers Compose runs from this image, while the tests get it from tsan's test preset. Then the stage runs the workflow, in place of its configure, build and ctest lines. The fuzz stage configures and builds its preset, which names its two targets, so the stage doesn't list them any more. The tidy stage configures and builds its preset too, and clang-tidy reads the compile commands from the tidy folder, where they are now. The coverage stage builds its preset, with Clang's counters. Further down, the profiling stage configures and builds the profile preset, which builds the world server alone, and the profiling image copies the server from the profile folder. In the sanitizers' Compose file, the build argument is the preset now, and each server runs from its preset's folder, the database tests too, as the main Compose file runs them from the build folder. In CI, the gate skips a check that has passed on this tree before, and it looks for the sanitizers' markers by their presets' names now. The sanitize job's matrix names the two presets, and each leg hands its preset to the Docker build as an environment variable. A cache key can hold a preset's name as it is, so the step that swapped the comma in address comma undefined for a dash goes, and the ccache and marker keys use the preset. The fuzz job runs the fuzzers from the fuzz folder. And the coverage script runs the coverage test preset, which already says where each test writes its counts, so the script doesn't set that variable any more. It merges the counts from the coverage folder, and reads the programs from there too, so that code no test reaches is counted, at zero.
10:13 Let's run the sanitize stage the way CI does, with the thread sanitizer's preset as its build argument. It builds the game from the start with ThreadSanitizer, in Ubuntu with Clang, which takes a while, and grep keeps the line that sums up the tests. They pass under the thread sanitizer too, from a single cmake command in the Dockerfile.
C++23
10:34 Moving to C++23 starts with a number in the CMake file. The standard is twenty-three now, still required, so CMake stops at a compiler without a C++23 mode. One that has the mode but not all of its parts gets further, which the doctor script deals with at the end. C++23 was published in twenty twenty-four, and the compilers have been catching up with it a part at a time since, which we're going to run into today. The first use of it is in the client, where a string has a contains function now. So the client's check for a word in an animation's name says what it means, where we compared find with n pos, the value find returns when there's nothing to find. The storyteller's check for the end of a sentence gets contains as well, on a string view of the characters that end one.
11:22 The release workflow builds the game as C++23, with Apple's Clang, and grep keeps the summary of the tests again, and the C++ libraries we fetch build with our standard too. It builds, and the tests pass, the client's along with the servers'.
A lambda that waits again
11:38 The world server's heartbeat is a lambda that registers the world with Consul, then sets a timer for two seconds and hands the timer the lambda again, so it runs each two seconds. Inside its own body, a lambda has no name to hand over, so we kept it in a std function, a box that holds anything callable, and calls it through a pointer, and the lambda captured the box. That's what the functional header was for, and it goes. In C++23, a member function can take its object as an explicit first parameter, marked this, and a lambda's call is a member function, so the lambda gets its own object, which we call self. The feature's known as deducing this, as self's type is deduced like a template's, so it's the lambda's own type, without a std function in between. Over it, we say why: the lambda gets its own object as its first parameter, self, so that it can wait on the timer again. And at the bottom, it hands self to the timer. Self is a copy of the lambda, which is cheap, as it captures by reference. The wait for the players to leave during a handover becomes one too, and hands self to its timer each hundred milliseconds. And the saver's tick, which saves the players to MySQL each five seconds, gets that change too, and loses its functional header.
12:51 Let's build it, and have grep keep the lines with the errors. It doesn't compile, and the first error is a strange one: checking a constraint depends on the answer to that check. Then Clang finds no async wait it can call with the saver's lambda, inside the lambda's body and where we hand it over. Async wait is a template, constrained by a concept that asks whether what we hand it can be called with an error code, and what it returns. The saver's lambda goes to async wait before it's ever called, and its return type is deduced from its body, so to answer, the compiler has to compile the body. The body calls async wait with the lambda, which asks the question again. The world server's two lambdas built, as each is called once first, and its early return makes it void before the body reaches async wait.
13:41 So the lambdas say what they return, in their signature, where the concept can read it without the body. The world server's two don't need it, but we name it there too, so they don't depend on where their early return is. An arrow and void after the parameters is the lambda's return type, written out. Over it, we add the reason: it names its return type, which async wait checks, so that it doesn't depend on its early return coming first. The handover's wait gets its void too, and so does the saver's tick, with a shorter note: self is the lambda, which waits on the timer again, with its return type named, as async wait checks it.
14:19 This time, the release workflow builds it, with grep keeping the summary of the tests, and they pass. With MySQL, Redis and Consul up in Docker, we start the world server for a few seconds, and it says what it's listening on. Its heartbeat registers the world with Consul, from the lambda that now hands its own object to the timer.
14:40 The sanitizers build in Docker, as CI does, and with Clang, so let's build that stage too, and keep its errors. It compiles the libraries first, which takes a few minutes. Then Clang eighteen stops on our lambdas: it can't compile this l-value expression yet, it says, where each hands its own object to async wait. Clang eighteen accepts deducing this, and then can't generate the code for this case. We tried it on the versions of Clang that Ubuntu has, and nineteen and newer compile it.
15:09 So the checks move to a newer Clang. The clang stage installs Clang twenty-one, the version Ubuntu twenty-six oh four's own clang package depends on, with its runtime libraries, which the sanitizers need, and LLVM's tools, such as the coverage ones. Its folder goes first on the path, so clang means Clang twenty-one in each stage built on it. Over it, we add why: Clang twenty-one is Ubuntu twenty-six oh four's own, and Clang eighteen crashes generating the code for a lambda that hands its own object to Asio. Further down, the tidy stage installs clang-tidy twenty-one to match, so it reads our code the way that compiler does.
15:48 With Clang twenty-one, the sanitize stage builds the game with the address and undefined behaviour sanitizers, and runs the tests, which takes a while again. They pass, with the timers' lambdas built into the server like the rest of its code.
Grids by row and column
16:02 Next, the grids, which are the other place C++23 helps. The terrain keeps the heights of its corners in a single vector, a row after another, and the trees' squares, the map's pixels, the chunks and the heights the sea reads are each kept that way, in a single array. Each read works out j times the width, plus i, by hand. C++23's standard library has mdspan, a view that reads a flat array in several dimensions. We give it a name of our own, Grid, a template over the type of the cells, which is an mdspan of two dimensions, with their sizes known as the program runs, as ints. Over it, we write how to read it: a grid kept in a single array, a row after another, where grid j comma i is the i-th of row j. A corner of the terrain, which the server and the client ask for whenever they need a height, now comes from a view over its vector, with a row for each line of corners. The view is read with two indexes in a single pair of square brackets, which C++23 allows, and which C++20 would have read as the comma operator, keeping the second index alone. In the terrain's constructor, we make a view over the corners' vector, with a row of corners for each line of cells, plus one, and write each height by its row and its column. Planting the trees makes a view over their squares, each holding the index of its tree, or minus one for none. Checking whether a point is inside a trunk reads them through a view of constant ints, as that function is const, so the vector it sees is constant too. We make each view where it's needed and don't keep it in the class next to its vector, as a copy of the terrain would keep pointing into the vector it was copied from. The map's pixels come from raylib, as a pointer into an image, so the grid goes over the pointer, with as many rows as columns. We write each pixel by down and across, and each tree's dark spot by its row and column. The ground is drawn in chunks, a square grid of meshes, so the chunks get a grid of their own, over their vector. Each chunk's ground goes in by its row and column, at its corner of the terrain, and further down, each tree goes into the chunk under its trunk, which we find by its row and column too. Last, the sea reads the ground's heights from a texture. So the heights go into a vector of floats first, through a grid of their own, and then the vector goes to the GPU as an image of one float a pixel.
18:25 On the Mac, the release workflow builds it, and the tests pass. CI builds in Docker, though, on Ubuntu twenty-six oh four, with GCC fifteen, so let's build the image the way CI does. GCC can't find an mdspan header at all. The library Apple's Clang uses, libc++, has had mdspan since LLVM seventeen, while GCC's library got it in GCC sixteen, which came out in April, after Ubuntu twenty-six oh four had settled on GCC fifteen. So a part of C++23 can be in one compiler's library and not yet in another's, and here it's the Docker build, with CI's compiler, that shows it.
19:07 Instead of waiting for GCC sixteen, we're going to write the grid ourselves, and as it's ours, it can check its indexes. A grid of two rows of three sits in memory a row after the other. Ask for row zero, column three, one past the end of the row, and the arithmetic lands on the first cell of row one. That cell is inside the array, so AddressSanitizer reports nothing, and the program carries on with the wrong cell. A grid that keeps its rows and its columns can check the row against its rows and the column against its columns, and stop the program there.
19:38 So Grid becomes a class of our own. The mdspan header goes, and in comes abseil's check header, for CHECK, which stops the program with a message when a condition is false, and unlike assert, stays on in a release build, which is what the servers ship as. The class keeps the name Grid, so none of the code that reads grids changes. Its constructor takes a pointer to the cells, then the rows and the columns, in the order mdspan took them. Its subscript operator takes two indexes, which is the C++23 part, and one GCC has had since version twelve. It's const and returns a reference into the cells, as a view's does: the view doesn't change, while the cells can. It checks the row against the rows and the column against the columns, and if one is out, it says which indexes it got, and the grid's size. Then it does the arithmetic, in one place now. It keeps the pointer and the two sizes. Over the class, we add the rest of the reason: like a span, it points into the array and doesn't keep it. And an index outside its row or column stops the program, as a column past the end of a row would still be inside the array, in the next row. Checking both indexes on each read is a cost I'm happy with here. I'd much prefer the server to stop at that line, with everyone on it, over walking players through the wrong trees until someone notices. The terrain library links abseil's check, publicly, as its header uses it. Now, a quick test that the grid reads by row and column, and stops outside them. GoogleTest runs suites whose names end in death test first, as their tests fork the process, which is safest before other tests have started threads. It makes a grid of two rows of three over a vector of six ints. It writes a seven into the first cell of row one, and checks that it reads back through the grid. That read is in parentheses, and over it, we write why: a comma inside square brackets still splits a macro's arguments, so each read goes in parentheses. It should also be the fourth cell of the vector, as row one starts after the three cells of row zero. Then expect death runs a read past the row in a child process, and passes when the child stops with a message that has the word outside.
21:53 The release workflow builds it on the Mac, and runs the tests. Running the grid's test on its own, it passes, so the child process stopped at column three, with its message. Then in Docker, with GCC fifteen, and with a flag that has Docker run the test stage even when it has it cached, the game builds without mdspan now, and the tests pass there too.
Checking the compiler
22:16 The doctor script is where a new machine starts, so it's where a compiler that's too old should show up. C++23 has reached the compilers a part at a time, as we've seen three times today, so the doctor script, which checks a machine has what the game needs, should ask the compiler for the parts we use. It looks at the compiler the release preset builds with: the one the CXX variable names, if it's set, and c plus plus otherwise, the system's default, which is GCC on Ubuntu and Apple's Clang on a Mac. Over it, we write why: the game is C++23, and two of the parts it uses came late to the compilers, GCC fourteen, Clang eighteen and Xcode sixteen point three. They're a member function that takes its object as a parameter, and a subscript operator with two indexes, so we ask the compiler to compile both. If there's no such program, it says how to get one, as it did before: the command line tools on a Mac, and build essential on Ubuntu, which goes into the install command at the end. Otherwise, it writes a small struct, with one of each. It pipes the struct to the compiler as C++23, from standard input, which has no file name to tell the compiler the language, so dash x c plus plus says it. The flag after that has it check the code and write nothing, while the errors go nowhere. I prefer asking the compiler to keeping a table of versions, which would go out of date. If it compiles, the compiler's line gets its tick. If not, on a Mac it asks for Xcode sixteen point three or newer, and on Ubuntu, for GCC fourteen, named in the CXX variable before CMake's first run. CMake keeps the compiler of its first run in the build folder, which is why it has to come first. Ubuntu twenty-four oh four's own GCC thirteen can't compile the struct, while its g++ fourteen can. And its hint for tests without a screen runs the release test preset.
24:09 On the Mac, the doctor checks the tools to build with, and Apple's Clang twenty-one compiles the struct, so it gets its tick.
The docs
24:18 Last, the game's docs, starting with the Getting started page. Getting started installs g++ fourteen on Ubuntu twenty-four oh four, and has the shell name it in CXX, and it builds with the release preset, with a line on where the others are. And the choice gets decision record twenty-six, C++23 for the servers and the client, with each build named in a preset. Its context is the code that C++23 tidied, and the seven builds with their flags spelled out. And we use a part of C++23 once the compilers we build with have it, in the versions our platforms ship, which today cost us mdspan, with the doctor script checking the parts we use. mdspan is the alternative we tried, which built on the Mac and not with GCC fifteen, and it wouldn't check an index against its row the way Grid does. Std expected is the obvious one we didn't take, as status or already carries a code and a message. What it costs us is GCC fourteen on Ubuntu twenty-four oh four, a void on each of those lambdas, and a check of both indexes on each read of a grid. And the checks need Clang nineteen or newer, so the Dockerfile builds them with Clang twenty-one. It supersedes record one, which chose C++20, so record one's row says so in the index, and twenty-six is the newest row.
Wrap-up
25:39 Today, each way the game is built got a preset and a build folder of its own, with workflows that configure, build and test in one command. The Dockerfile and CI build with them now. Then the game moved to C++23, and its libraries with it, as they build with our standard. The timers' lambdas take their own object as self, and name their return type, as async wait checks it, and the checks build with Clang twenty-one, as eighteen crashed on them. The grids read by row and column, through a Grid of our own, as GCC fifteen has no mdspan, and it checks each index against its row or column. The doctor script asks the compiler for the parts of C++23 we use, and record twenty-six says why we made the move.
Playing it
27:13 Let me know in the comments what you'd like to see next, and if you want to follow along with the series, subscribe to the channel. I hope you find this useful, and thanks for watching.