# Jeff Preshing

C is a simple language. You're only allowed to have one function with each name. C++, on the other hand, gives you much more flexibility: You can have multiple functions ...

This is one page of public article previews, not the complete archive. Follow Next page to continue. Summaries are not the original full articles.

## How C++ Resolves a Function Call

DevFeed: [How C++ Resolves a Function Call](<https://devfeed.tech/articles/how-c-resolves-a-function-call-21020.md>)

Original publisher: [Read original article](<https://preshing.com/20210315/how-cpp-resolves-a-function-call>)

Author: Jeff Preshing

Published: 2021-03-15T12:10:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [Tutorial](<https://devfeed.tech/topics/tutorial.md>), [Algorithms](<https://devfeed.tech/topics/algorithms.md>), [Type Argument](<https://devfeed.tech/topics/type-argument.md>), [Jule](<https://devfeed.tech/topics/jule.md>)

Tags: [algorithm](<https://devfeed.tech/tags/algorithm.md>), [built-in](<https://devfeed.tech/tags/built-in.md>), [c](<https://devfeed.tech/tags/c.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [call](<https://devfeed.tech/tags/call.md>), [career](<https://devfeed.tech/tags/career.md>), [compile](<https://devfeed.tech/tags/compile.md>), [compiler](<https://devfeed.tech/tags/compiler.md>), [features](<https://devfeed.tech/tags/features.md>), [function](<https://devfeed.tech/tags/function.md>), [functions](<https://devfeed.tech/tags/functions.md>), [namespaces](<https://devfeed.tech/tags/namespaces.md>), [operator](<https://devfeed.tech/tags/operator.md>), [operators](<https://devfeed.tech/tags/operators.md>), [runtime](<https://devfeed.tech/tags/runtime.md>), [sort](<https://devfeed.tech/tags/sort.md>), [string](<https://devfeed.tech/tags/string.md>), [strings](<https://devfeed.tech/tags/strings.md>), [template](<https://devfeed.tech/tags/template.md>), [templates](<https://devfeed.tech/tags/templates.md>)

### AI overview

C++ resolves function calls at compile time through a sequence of steps: name lookup gathers candidates, including functions found through argument-dependent lookup for unqualified calls; template argument deduction and substitution turn viable templates into functions or remove them when deduction or substitution fails (SFINAE); and overload resolution filters by argument compatibility and constraints before selecting the best viable function. The example shows a namespace function and a function template with identical parameter types; the non-template wins the tie. Better argument conversions take precedence over template status, and a more specialized template can win when earlier rules do not decide the call. If no unambiguous best candidate exists, compilation fails. The article presents a high-level explanation and notes that detailed rules for lookup, conversions, deduction, and specialization are omitted.

### Source excerpt

C is a simple language. You're only allowed to have one function with each name. C++, on the other hand, gives you much more flexibility: You can have multiple functions with the same name (overloading). You can overload built-in operators like + and ==. You can write function templates. Namespaces help you avoid naming conflicts. I like these C++ features. With these features, you can make str1 + str2 return the concatenation of two strings. You can have a pair of 2D points, and another pair of 3D points, and overload dot(a, b) to work with either type. You can have a bunch of array-like classes and write a single sort function template that works with all of them. But when you take advantage of these features, it's easy to push things too far. At some point, the compiler might unexpectedly reject your code with errors like: error C2666: 'String::operator ==': 2 overloads have similar conversions note: could be 'bool String::operator ==(const String &) const' note: or 'built-in C++ operator==(const char *, const char *)' note: while trying to match the argument list '(const String, const char *)' Like many C++ programmers, I've struggled with such errors throughout my career. Each time it happened, I would usually scratch my head, search online for a better understanding, then change the code until it compiled. But more recently, while developing a new runtime library for Plywood, I was thwarted by such errors over and over again. It became clear that despite all my previous experience with C++, something was missing from my understanding and I didn't know what it was. Fortunately, it's now 2021 and information about C++ is more comprehensive than ever. Thanks especially to cppreference.com, I now know what was missing from my understanding: a clear picture of the hidden algorithm that runs for every function call at compile time. This is how the compiler, given a function call expression, figures out exactly which function to call: may performargument-dependentloo

## Flap Hero Code Review

DevFeed: [Flap Hero Code Review](<https://devfeed.tech/articles/flap-hero-code-review-21019.md>)

Original publisher: [Read original article](<https://preshing.com/20201210/flap-hero-code-review>)

Author: Jeff Preshing

Published: 2020-12-10T20:23:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [C++](<https://devfeed.tech/topics/c-plus-plus.md>), [Code](<https://devfeed.tech/topics/code.md>), [Game engine](<https://devfeed.tech/topics/game-engine.md>), [Framework](<https://devfeed.tech/topics/framework.md>), [OpenGL](<https://devfeed.tech/topics/opengl.md>), [GitHub](<https://devfeed.tech/topics/github.md>), [Android](<https://devfeed.tech/topics/android.md>), [iOS](<https://devfeed.tech/topics/ios.md>), [Linux](<https://devfeed.tech/topics/linux.md>), [macOS](<https://devfeed.tech/topics/macos.md>)

Tags: [android](<https://devfeed.tech/tags/android.md>), [architecture](<https://devfeed.tech/tags/architecture.md>), [build](<https://devfeed.tech/tags/build.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [code](<https://devfeed.tech/tags/code.md>), [framework](<https://devfeed.tech/tags/framework.md>), [general](<https://devfeed.tech/tags/general.md>), [github](<https://devfeed.tech/tags/github.md>), [ios](<https://devfeed.tech/tags/ios.md>), [linux](<https://devfeed.tech/tags/linux.md>), [macos](<https://devfeed.tech/tags/macos.md>)

### AI overview

This code review examines Flap Hero, a small C++ game built without an existing game engine. It explains the project's architecture, reusable modules, dependencies, gameplay state management, platform-specific projects, and deliberately limited subsystem design. The article also discusses the use of Plywood, OpenGL, and advanced C++ features in lower-level modules.

### Source excerpt

Flap Hero is a small game written entirely in C++ without using an existing game engine. All of its source code is available on GitHub. I think it can serve as an interesting resource for novice and intermediate game developers to study. In this post, I'll explain how Flap Hero's code is organized, how it differs from larger game projects, why it was written that way, and what could have been done better. Very little information in this post is specific to C++. Most of it would still be relevant if Flap Hero was written in another language like C#, Rust or plain C. That said, if you browse (or build) the source code, you will need some fluency in C++. Learn C++ and Learn OpenGL are two great resources for beginners. For the most part, Flap Hero's source code sticks to a fairly straightforward subset of C++, but the deeper you go into its low-level modules (like runtime), the more you'll encounter advanced C++ features like templates and SFINAE. General Architecture Flap Hero was developed using Plywood, a C++ framework that helps organize code into reusable modules. Each yellow box in the diagram below represents a Plywood module. The blue arrows represent dependencies. platform runtime image math plywood repo flapGame glfwFlap GameFlow.cpp GameState.cpp Collision.cpp Text.cpp FlapHero repo Public.h glfw soloud glad assimp Main.cpp iOS project Android project iOS project iOS project Windows,Linux& macOS Assets.cpp GLHelpers.cpp The biggest chunk of Flap Hero's game code is located in the flapGame module, which contains roughly 6400 physical lines of code. The two most important source files in the flapGame module are GameFlow.cpp and GameState.cpp. All the state for a single gameplay session is held inside a single GameState object. This object is, in turn, owned by a GameFlow object. The GameFlow can actually own two GameState objects at a given time, with both gameplay sessions updating concurrently. This is used to achieve an animated "split screen" effect during

## A Small Open Source Game In C++

DevFeed: [A Small Open Source Game In C++](<https://devfeed.tech/articles/a-small-open-source-game-in-c-21018.md>)

Original publisher: [Read original article](<https://preshing.com/20201126/a-small-open-source-game-in-cpp>)

Author: Jeff Preshing

Published: 2020-11-26T12:52:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [Open Source](<https://devfeed.tech/topics/open-source.md>), [Game engine](<https://devfeed.tech/topics/game-engine.md>)

Tags: [3d](<https://devfeed.tech/tags/3d.md>), [assets](<https://devfeed.tech/tags/assets.md>), [audio](<https://devfeed.tech/tags/audio.md>), [build](<https://devfeed.tech/tags/build.md>), [built-in](<https://devfeed.tech/tags/built-in.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [dependencies](<https://devfeed.tech/tags/dependencies.md>), [desktop](<https://devfeed.tech/tags/desktop.md>), [download](<https://devfeed.tech/tags/download.md>), [engine](<https://devfeed.tech/tags/engine.md>), [fonts](<https://devfeed.tech/tags/fonts.md>), [framework](<https://devfeed.tech/tags/framework.md>), [free](<https://devfeed.tech/tags/free.md>), [game](<https://devfeed.tech/tags/game.md>), [game-development](<https://devfeed.tech/tags/game-development.md>), [github](<https://devfeed.tech/tags/github.md>), [graphics](<https://devfeed.tech/tags/graphics.md>), [i-o](<https://devfeed.tech/tags/i-o.md>), [open-source](<https://devfeed.tech/tags/open-source.md>), [small](<https://devfeed.tech/tags/small.md>)

### AI overview

Flap Hero is a small, open-source C++ mobile game built with Plywood, a module-oriented framework rather than a game engine. It uses third-party libraries for game-specific tasks: Assimp loads 3D models, SoLoud handles audio, stb loads textures and fonts, and GLFW provides desktop windowing and input. Plywood provides the workspace for integrating those dependencies with custom and built-in modules; the excerpt names runtime, math, and image, and says runtime supplies cross-platform I/O, strings, and containers as an alternative to standard C/C++ runtimes. The author attributes the game's small download, fast loading, low memory use, and responsive performance to avoiding an existing game engine. Plywood is still a work in progress, with third-party integration and building on other machines identified as weak spots; a GUI build manager with package-manager integration is a proposed improvement. The game source is under the MIT license, while its assets are dedicated to the public domain.

### Source excerpt

I just released a mobile game called Flap Hero. It's a Flappy Bird clone with cartoony graphics and a couple of twists: You can go in the pipes (wow!) and it takes two collisions to end the game. Flap Hero is free, quick to download (between 3 - 5 MB) and opens instantly. Give it a try! Flap Hero is open source, too. Its source code is released under the MIT license and its assets (3D models, sounds, music) are dedicated to the public domain. Do whatever you want with them! Everything's available on GitHub. I'm releasing this game to promote Plywood, an open source C++ framework I released a few months ago. Flap Hero was made using Plywood. How Flap Hero Uses Plywood If you only read up to this point, you might think that Plywood is a game engine. It isn't! Plywood is best described as a "module-oriented" C++ framework. It gives you a workspace, a set of built-in modules and some (optional) code generation tricks. Plywood currently has 36 built-in modules, none of which are specific to game development. For game-specific functionality, Flap Hero relies on several excellent third-party libraries: Assimp to load 3D models, SoLoud for audio, stb to load textures and fonts, and GLFW for desktop windowing & input. If Flap Hero relies on third-party libraries, you might be wondering, what's the point of Plywood? Well, those libraries have to be integrated into something. In Plywood, that something is the Plywood workspace. In this workspace, you can create your own modules that depend on other Plywood modules as well as on third-party libraries. You can then instantiate those modules in build folders, and they'll bring all their dependencies along with them. In addition to the aforementioned libraries, Flap Hero uses several built-in Plywood modules such as runtime, math and image. Plywood's runtime module offers an alternative to the standard C and C++ runtimes, providing lean cross-platform I/O, strings, containers and more. The math module provides vectors, matrices, q

## Automatically Detecting Text Encodings in C++

DevFeed: [Automatically Detecting Text Encodings in C++](<https://devfeed.tech/articles/automatically-detecting-text-encodings-in-c-21017.md>)

Original publisher: [Read original article](<https://preshing.com/20200727/automatically-detecting-text-encodings-in-cpp>)

Author: Jeff Preshing

Published: 2020-07-27T20:10:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [Encoding](<https://devfeed.tech/topics/encoding.md>)

Tags: [ascii](<https://devfeed.tech/tags/ascii.md>), [automatically](<https://devfeed.tech/tags/automatically.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [encoding](<https://devfeed.tech/tags/encoding.md>), [shift](<https://devfeed.tech/tags/shift.md>), [text](<https://devfeed.tech/tags/text.md>), [unix](<https://devfeed.tech/tags/unix.md>), [utf-8](<https://devfeed.tech/tags/utf-8.md>), [windows](<https://devfeed.tech/tags/windows.md>)

### AI overview

Plywood's `openTextForReadAutodetect()` examines up to 4 KB, scores candidate interpretations, and converts input on the fly to BOM-free UTF-8 with `\n` line endings. It first favors valid UTF-8 without control codes; later it compares UTF-8 with plain bytes, then scores 8-bit, little-endian UTF-16, and big-endian UTF-16 using whitespace, ASCII, errors, control codes, and non-BMP characters. The author describes the scoring weights as made-up and not necessarily optimal. Detection currently treats non-UTF-8 8-bit text as Windows-1252 and does not support Shift JIS, so ambiguous files can still be misidentified. On a hand-made 50-file suite, Plywood detected all files; Notepad++ detected 38, Sublime Text 42, Visual Studio Code 40, and Windows Notepad 42. The author cautions that the suite was tailored to Plywood and many failures involved UTF-16 files without a BOM.

### Source excerpt

Consider the lowly text file. This text file can take on a surprising number of different formats. The text could be encoded as ASCII, UTF-8, UTF-16 (little or big-endian), Windows-1252, Shift JIS, or any of dozens of other encodings. The file may or may not begin with a byte order mark (BOM). Lines of text could be terminated with a linefeed character \n (typical on UNIX), a CRLF sequence \r\n (typical on Windows) or, if the file was created on an older system, some other character sequence. Sometimes it's impossible to determine the encoding used by a particular text file. For example, suppose a file contains the following bytes: A2 C2 A2 C2 A2 C2 This could be: a UTF-8 file containing "ccc" a little-endian UTF-16 (or UCS-2) file containing "ꋂꋂꋂ" a big-endian UTF-16 file containing "슢슢슢" a Windows-1252 file containing "ÂcÂcÂc" That's obviously an artificial example, but the point is that text files are inherently ambiguous. This poses a challenge to software that loads text. It's a problem that has been around for a while. Fortunately, the text file landscape has gotten simpler over time, with UTF-8 winning out over other character encodings. More than 95% of the Internet is now delivered using UTF-8. It's impressive how quickly that number has changed; it was less than 10% as recently as 2006. UTF-8 hasn't taken over the world just yet, though. The Windows Registry editor, for example, still saves text files as UTF-16. When writing a text file from Python, the default encoding is platform-dependent; on my Windows PC, it's Windows-1252. In other words, the ambiguity problem still exists today. And even if a text file is encoded in UTF-8, there are still variations in format, since the file may or may not start with a BOM and could use either UNIX-style or Windows-style line endings. How the Plywood C++ Framework Loads Text Plywood is a cross-platform open-source C++ framework I released two months ago. When opening a text file using Plywood, you have a couple of o

## I/O in Plywood

DevFeed: [I/O in Plywood](<https://devfeed.tech/articles/i-o-in-plywood-21016.md>)

Original publisher: [Read original article](<https://preshing.com/20200708/io-in-plywood>)

Author: Jeff Preshing

Published: 2020-07-08T12:15:00Z

Content type: tutorial

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [IO](<https://devfeed.tech/topics/io.md>), [Encoding](<https://devfeed.tech/topics/encoding.md>)

Tags: [c](<https://devfeed.tech/tags/c.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [conversion](<https://devfeed.tech/tags/conversion.md>), [encoding](<https://devfeed.tech/tags/encoding.md>), [framework](<https://devfeed.tech/tags/framework.md>), [i-o](<https://devfeed.tech/tags/i-o.md>), [libraries](<https://devfeed.tech/tags/libraries.md>), [library](<https://devfeed.tech/tags/library.md>), [low-level](<https://devfeed.tech/tags/low-level.md>), [memory](<https://devfeed.tech/tags/memory.md>), [module](<https://devfeed.tech/tags/module.md>), [network](<https://devfeed.tech/tags/network.md>), [open-source](<https://devfeed.tech/tags/open-source.md>), [operating-system](<https://devfeed.tech/tags/operating-system.md>), [performance-tuning](<https://devfeed.tech/tags/performance-tuning.md>), [platform-api](<https://devfeed.tech/tags/platform-api.md>), [runtime](<https://devfeed.tech/tags/runtime.md>), [standard](<https://devfeed.tech/tags/standard.md>), [storage](<https://devfeed.tech/tags/storage.md>), [threads](<https://devfeed.tech/tags/threads.md>)

### AI overview

Plywood provides a cross-platform C++ I/O alternative to the standard C and C++ libraries, which remain optional. Its buffered OutStream writes raw bytes to an output pipe; StdOut::text adds newline conversion, while StdOut::binary does not. Streams are not thread-safe, so callers must use each from one thread or provide mutual exclusion, and lines are not flushed automatically. Text adapters convert between UTF-8 in memory and formats such as UTF-16 with configurable byte order, BOM, and line endings. Input autodetection uses a BOM or heuristics for UTF-8 versus UTF-16 and returns UTF-8 lines. Reading each line into a String may allocate repeatedly; parsing views into a loaded String can reduce copies, provided the source remains alive. The article also describes memory-backed writers and a single-allocation optimization for short strings. At the time described, Plywood lacks bidirectional streams, uses synchronous flushing, and has incomplete support for encodings beyond UTF-8 and UTF-16.

### Source excerpt

Plywood is an open-source C++ framework I released a few weeks ago. It includes, among other things, a runtime module that exposes a cross-platform API for I/O, memory, threads, process management and more. This post is about the I/O part. For those who don't know, I/O stands for input/output, and refers to the part of a computer system that either writes serialized data to or reads serialized data from an external interface. The external interface could be a storage device, pipe, network connection or any other type of communication channel. Typically, it's the operating system's responsibility to provide low-level I/O services to an application. But there's still plenty of work that needs to happen at the application level, such as buffering, data conversion, performance tuning and exposing an interface that makes life easier on application programmers. That's where Plywood's I/O system comes in. Of course, standard C++ already comes with its own input/output library, as does the standard C runtime, and most C and C++ programmers are quite familiar with those libraries. Plywood's I/O system is meant serve as an alternative to those libraries. Those libraries were originally developed in 1984 and the early 1970s, respectively. They've stood the test of time incredibly well, but I don't think it's outrageous to suggest that, hey, maybe some innovation is possible here. To be clear, when you build a project using Plywood, you aren't required to use Plywood's I/O system - you can still use the standard C or C++ runtime library, if you prefer. I'm sure this blog post will seem dry for some (or many) readers - but not for me! I like this topic, and I'm willing bet that there are other low-level I/O wonks out there who will find it interesting as well. So let's jump in. Writing Raw Bytes to Standard Output The following program writes "Hello!\n" to standard output as a raw sequence of 7 bytes. No newline conversion or character encoding conversion is performed. Writing t

## A New Cross-Platform Open Source C++ Framework

DevFeed: [A New Cross-Platform Open Source C++ Framework](<https://devfeed.tech/articles/a-new-cross-platform-open-source-c-framework-21015.md>)

Original publisher: [Read original article](<https://preshing.com/20200526/a-new-cross-platform-open-source-cpp-framework>)

Author: Jeff Preshing

Published: 2020-05-26T11:50:00Z

Content type: release

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [Open Source](<https://devfeed.tech/topics/open-source.md>), [CMake](<https://devfeed.tech/topics/cmake.md>), [modules](<https://devfeed.tech/topics/modules.md>), [container](<https://devfeed.tech/topics/container.md>), [Process](<https://devfeed.tech/topics/process.md>)

Tags: [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [cross-platform](<https://devfeed.tech/tags/cross-platform.md>), [framework](<https://devfeed.tech/tags/framework.md>), [open-source](<https://devfeed.tech/tags/open-source.md>), [software](<https://devfeed.tech/tags/software.md>)

### AI overview

Plywood is an open source C++ framework and workspace for building multiple applications and sharing modules across them; it is not itself a game engine. Its 36 optional built-in modules include platform abstractions, math, JSON, audio and image processing, while its runtime provides facilities such as cross-platform I/O and process creation. A reflection system uses code generation to expose type metadata for generic operations such as loading JSON. The examples use Cairo and Libavcodec, and the source says they build and run on Windows, Linux and macOS. Plywood uses CMake without requiring users to write CMake scripts. The author notes that module definition currently requires an undocumented C++ API, reflection code generation must be run manually before compiling, and some graphics and audio modules remain proprietary. The excerpt presents Plywood as viable for relatively new cross-platform C++ projects, with a need to follow development and consult source code where documentation is incomplete.

### Source excerpt

For the past little while - OK, long while - I've been working on a custom game engine in C++. Today, I'm releasing part of that game engine as an open source framework. It's called the Plywood framework. View the documentation View on GitHub Please note that Plywood, by itself, is not a game engine! It's a framework for building all kinds of software using C++. For example, Plywood's documentation is generated with the help of a C++ parser, formatted by a Markdown parser, and runs on a custom webserver all written using Plywood. Integrating third-party libraries can a pain in C++, but Plywood aims to simplify it. Here's a short Plywood program that uses Cairo and Libavcodec to render a vector animation to a video file: And here's one that synthesizes a short music clip to an MP3: The source code for these examples is included in the Plywood repository, and everything builds and runs on Windows, Linux and macOS. Of course, Plywood also serves as the foundation for my (proprietary) game engine, which I call the Arc80 Engine. That's why Plywood came into existence in the first place. I haven't shipped a complete game using the Arc80 Engine yet, but I have made a number of prototypes with it. More on that later! What's Included In Plywood Plywood comes with: A workspace designed to help you reuse code between applications. A set of built-in modules providing cross-platform I/O, containers, process creation and more. A runtime reflection and serialization system. Here are a few more details about each component. The Workspace Most open source C++ projects are libraries that are meant to be integrated into other applications. Plywood is the opposite of that: It gives you a workspace into which source code and libraries can be integrated. A single Plywood workspace can contain several applications - a webserver, a game engine, a command-line tool. Plywood simplifies the task of building and sharing code between them. Plywood uses CMake under the hood, but you don't have t

## A Flexible Reflection System in C++: Part 2

DevFeed: [A Flexible Reflection System in C++: Part 2](<https://devfeed.tech/articles/a-flexible-reflection-system-in-c-part-2-21014.md>)

Original publisher: [Read original article](<https://preshing.com/20180124/a-flexible-reflection-system-in-cpp-part-2>)

Author: Jeff Preshing

Published: 2018-01-24T13:07:00Z

Content type: tutorial

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [class](<https://devfeed.tech/topics/class.md>), [Inheritance](<https://devfeed.tech/topics/inheritance.md>), [Boilerplate](<https://devfeed.tech/topics/boilerplate.md>), [Closure](<https://devfeed.tech/topics/closure.md>)

Tags: [built-in](<https://devfeed.tech/tags/built-in.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [flexible](<https://devfeed.tech/tags/flexible.md>), [macros](<https://devfeed.tech/tags/macros.md>), [reflection](<https://devfeed.tech/tags/reflection.md>), [runtime](<https://devfeed.tech/tags/runtime.md>), [support](<https://devfeed.tech/tags/support.md>), [system](<https://devfeed.tech/tags/system.md>), [type](<https://devfeed.tech/tags/type.md>)

### AI overview

The excerpt shows how the C++11 reflection system adds support for new types through type descriptors. For `double`, define a `getPrimitiveDescriptor<double>()` specialization that returns a descriptor with the type name, size, and dump behavior. Primitive specializations can live in separate `.cpp` files, though the author cautions that specialization rules still apply. For `std::unique_ptr<T>`, a partial `TypeResolver` specialization creates a descriptor per target type; templated lambda helpers dereference each specialization without depending on the standard library's internal representation. The article says `std::vector<>` uses a similar descriptor pattern with helpers for element count and access. It also describes a `TypeKey` function table used in the author's serializer for descriptor identity and object construction/destruction. Reflection relies on member-listing macros, which can become outdated; the author's alternative is a Python script that generates them from marked header sections.

### Source excerpt

In the previous post, I presented a basic system for runtime reflection in C++11. The post included a sample project that created a type descriptor using a block of macros: // Define Node's type descriptor REFLECT_STRUCT_BEGIN(Node) REFLECT_STRUCT_MEMBER(key) REFLECT_STRUCT_MEMBER(value) REFLECT_STRUCT_MEMBER(children) REFLECT_STRUCT_END() At runtime, the type descriptor was found by calling reflect::TypeResolver<Node>::get(). This reflection system is small but very flexible. In this post, I'll extend it to support additional built-in types. You can clone the project from GitHub to follow along. At the end, I'll discuss other ways to extend the system. Adding Support for double In Main.cpp, let's change the definition of Node so that it contains a double instead of an int: struct Node { std::string key; double value; std::vector<Node> children; REFLECT() // Enable reflection for this type }; Now, when we build the sample project, we get a link error: error: unresolved external symbol "reflect::getPrimitiveDescriptor<double>()" That's because the reflection system doesn't support double yet. To add support, add the following code near the bottom of Primitives.cpp, inside the reflect namespace. The highlighted line defines the missing function that the linker complained about. //-------------------------------------------------------- // A type descriptor for double //-------------------------------------------------------- struct TypeDescriptor_Double : TypeDescriptor { TypeDescriptor_Double() : TypeDescriptor{"double", sizeof(double)} { } virtual void dump(const void* obj, int /* unused */) const override { std::cout << "double{" << *(const double*) obj << "}"; } }; template <> TypeDescriptor* getPrimitiveDescriptor<double>() { static TypeDescriptor_Double typeDesc; return &typeDesc; } Now, when we run the program - which creates a Node object and dumps it to the console - we get the following output instead. As expected, members that were previously int are now do

## A Flexible Reflection System in C++: Part 1

DevFeed: [A Flexible Reflection System in C++: Part 1](<https://devfeed.tech/articles/a-flexible-reflection-system-in-c-part-1-21013.md>)

Original publisher: [Read original article](<https://preshing.com/20180116/a-primitive-reflection-system-in-cpp-part-1>)

Author: Jeff Preshing

Published: 2018-01-16T14:21:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [modules](<https://devfeed.tech/topics/modules.md>), [class](<https://devfeed.tech/topics/class.md>), [stl](<https://devfeed.tech/topics/stl.md>), [JSON](<https://devfeed.tech/topics/json.md>), [3D](<https://devfeed.tech/topics/3d.md>), [Tutorial](<https://devfeed.tech/topics/tutorial.md>)

Tags: [3d](<https://devfeed.tech/tags/3d.md>), [3d-rendering](<https://devfeed.tech/tags/3d-rendering.md>), [advanced](<https://devfeed.tech/tags/advanced.md>), [api](<https://devfeed.tech/tags/api.md>), [asset](<https://devfeed.tech/tags/asset.md>), [asset-pipeline](<https://devfeed.tech/tags/asset-pipeline.md>), [assets](<https://devfeed.tech/tags/assets.md>), [bugs](<https://devfeed.tech/tags/bugs.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [engine](<https://devfeed.tech/tags/engine.md>), [flexible](<https://devfeed.tech/tags/flexible.md>), [formats](<https://devfeed.tech/tags/formats.md>), [game](<https://devfeed.tech/tags/game.md>), [generic](<https://devfeed.tech/tags/generic.md>), [github](<https://devfeed.tech/tags/github.md>), [graphics](<https://devfeed.tech/tags/graphics.md>), [import](<https://devfeed.tech/tags/import.md>), [json](<https://devfeed.tech/tags/json.md>), [reflection](<https://devfeed.tech/tags/reflection.md>), [system](<https://devfeed.tech/tags/system.md>)

### AI overview

The post presents a small C++11 runtime reflection system built with macros and templates, motivated by serialization and also used for OpenGL ES rendering and importing JSON assets. A `REFLECT()` macro adds static descriptor and initialization members; `REFLECT_STRUCT_*()` macros define reflected fields. `TypeResolver<T>::get()` uses SFINAE to return a reflected struct's descriptor or a primitive descriptor. Descriptors store type name and size, with subclasses for extra details such as struct members and vector item types; `dump()` accepts a `const void*`, and callers must pair objects with the correct descriptor because invalid pointers can crash. The sample focuses on descriptor creation, structure, lookup, and console dumping; it is a separate, 242-line example rather than the engine implementation. The author targets C++11, so some detection logic remains awkward, and points readers seeking an existing solution to RTTR.

### Source excerpt

In this post, I'll present a small, flexible system for runtime reflection using C++11 language features. This is a system to generate metadata for C++ types. The metadata takes the form of TypeDescriptor objects, created at runtime, that describe the structure of other runtime objects. I'll call these objects type descriptors. My initial motivation for writing a reflection system was to support serialization in my custom C++ game engine, since I have very specific needs. Once that worked, I began to use runtime reflection for other engine features, too: 3D rendering: Every time the game engine draws something using OpenGL ES, it uses reflection to pass uniform parameters and describe vertex formats to the API. It makes graphics programming much more productive! Importing JSON: The engine's asset pipeline has a generic routine to synthesize a C++ object from a JSON file and a type descriptor. It's used to import 3D models, level definitions and other assets. This reflection system is based on preprocessor macros and templates. C++, at least in its current form, was not designed to make runtime reflection easy. As anyone who's written one knows, it's tough to design a reflection system that's easy to use, easily extended, and that actually works. I was burned many times by obscure language rules, order-of-initialization bugs and corner cases before settling on the system I have today. To illustrate how it works, I've published a sample project on GitHub: This sample doesn't actually use my game engine's reflection system. It uses a tiny reflection system of its own, but the most interesting part - the way type descriptors are created, structured and found - is almost identical. That's the part I'll focus on in this post. In the next post, I'll discuss how the system can be extended. This post is meant for programmers who are interested in how to develop a runtime reflection system, not just use one. It touches on many advanced features of C++, but the sample project

## How to Write Your Own C++ Game Engine

DevFeed: [How to Write Your Own C++ Game Engine](<https://devfeed.tech/articles/how-to-write-your-own-c-game-engine-21012.md>)

Original publisher: [Read original article](<https://preshing.com/20171218/how-to-write-your-own-cpp-game-engine>)

Author: Jeff Preshing

Published: 2017-12-18T12:54:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [Game engine](<https://devfeed.tech/topics/game-engine.md>), [Game Development](<https://devfeed.tech/topics/game-development.md>), [software-development](<https://devfeed.tech/topics/software-development.md>), [CMake](<https://devfeed.tech/topics/cmake.md>), [3D](<https://devfeed.tech/topics/3d.md>), [Unity](<https://devfeed.tech/topics/unity.md>), [Unreal Engine](<https://devfeed.tech/topics/unreal-engine.md>)

Tags: [2017](<https://devfeed.tech/tags/2017.md>), [3d](<https://devfeed.tech/tags/3d.md>), [advice](<https://devfeed.tech/tags/advice.md>), [approach](<https://devfeed.tech/tags/approach.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [complexity](<https://devfeed.tech/tags/complexity.md>), [engine](<https://devfeed.tech/tags/engine.md>), [game](<https://devfeed.tech/tags/game.md>), [game-development](<https://devfeed.tech/tags/game-development.md>), [game-engines](<https://devfeed.tech/tags/game-engines.md>), [gameplay](<https://devfeed.tech/tags/gameplay.md>), [mobile](<https://devfeed.tech/tags/mobile.md>), [programming](<https://devfeed.tech/tags/programming.md>), [serialization](<https://devfeed.tech/tags/serialization.md>), [write](<https://devfeed.tech/tags/write.md>)

### AI overview

The author's main advice is to keep engine development manageable: build a running program early, then let its architecture emerge through small iterations. An example progression starts with an SDL sample and a spinning cube, then adds model loading, controls, animation, platform support, and separate engine and game libraries. The author argues that moving existing code into modules is easier than designing a general architecture before requirements are clear. They also recommend allowing separate implementations when shared code gains complexity, and choosing among several dynamic dispatch patterns instead of enforcing one style. Serialization needs vary: simple games may load assets directly, while evolving formats and compatibility needs may call for versioned loaders or reflection-based generic serialization. Blender's SDNA reflection data supports compatibility across file versions; Cereal and Boost.Serialization are suggested for compact binary serialization without building a custom system.

### Source excerpt

Lately I've been writing a game engine in C++. I'm using it to make a little mobile game called Hop Out. Here's a clip captured from my iPhone 6. (Unmute for sound!) Hop Out is the kind of game I want to play: Retro arcade gameplay with a 3D cartoon look. The goal is to change the color of every pad, like in Q*Bert. Hop Out is still in development, but the engine powering it is starting to become quite mature, so I thought I'd share a few tips about engine development here. Why would you want to write a game engine? There are many possible reasons: You're a tinkerer. You love building systems from the ground up and seeing them come to life. You want to learn more about game development. I spent 14 years in the game industry and I'm still figuring it out. I wasn't even sure I could write an engine from scratch, since it's vastly different from the daily responsibilities of a programming job at a big studio. I wanted to find out. You like control. It's satisfying to organize the code exactly the way you want, knowing where everything is at all times. You feel inspired by classic game engines like AGI (1984), id Tech 1 (1993), Build (1995), and industry giants like Unity and Unreal. You believe that we, the game industry, should try to demystify the engine development process. It's not like we've mastered the art of making games. Far from it! The more we examine this process, the greater our chances of improving upon it. The gaming platforms of 2017 - mobile, console and PC - are very powerful and, in many ways, quite similar to one another. Game engine development is not so much about struggling with weak and exotic hardware, as it was in the past. In my opinion, it's more about struggling with complexity of your own making. It's easy to create a monster! That's why the advice in this post centers around keeping things manageable. I've organized it into three sections: Use an iterative approach Think twice before unifying things too much Be aware that serialization is

## Can Reordering of Release/Acquire Operations Introduce Deadlock?

DevFeed: [Can Reordering of Release/Acquire Operations Introduce Deadlock?](<https://devfeed.tech/articles/can-reordering-of-release-acquire-operations-introduce-deadlock-21011.md>)

Original publisher: [Read original article](<https://preshing.com/20170612/can-reordering-of-release-acquire-operations-introduce-deadlock>)

Author: Jeff Preshing

Published: 2017-06-12T11:34:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [c/c++](<https://devfeed.tech/topics/c-c-plus-plus.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [iteration](<https://devfeed.tech/topics/iteration.md>), [Process](<https://devfeed.tech/topics/process.md>)

Tags: [2](<https://devfeed.tech/tags/2.md>), [about](<https://devfeed.tech/tags/about.md>), [architectures](<https://devfeed.tech/tags/architectures.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [but](<https://devfeed.tech/tags/but.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [can](<https://devfeed.tech/tags/can.md>), [changes](<https://devfeed.tech/tags/changes.md>), [comes](<https://devfeed.tech/tags/comes.md>), [compare](<https://devfeed.tech/tags/compare.md>), [compiler](<https://devfeed.tech/tags/compiler.md>), [cpu](<https://devfeed.tech/tags/cpu.md>), [deadlock](<https://devfeed.tech/tags/deadlock.md>), [don-t](<https://devfeed.tech/tags/don-t.md>), [either](<https://devfeed.tech/tags/either.md>), [example](<https://devfeed.tech/tags/example.md>), [exchange](<https://devfeed.tech/tags/exchange.md>), [free](<https://devfeed.tech/tags/free.md>), [operations](<https://devfeed.tech/tags/operations.md>), [release](<https://devfeed.tech/tags/release.md>)

### AI overview

The post argues that a release store followed by an acquire spinlock attempt may be reordered under acquire/release rules, apparently allowing a thread to hold two locks and creating deadlock risk. The author believes C++ draft N4659 §4.7.2:18's recommendation that atomic updates eventually become visible rules out moving the store past a potentially infinite wait. Compiler Explorer showed no reordering by three major compilers, but the author says this is not proof. An update notes the standard says "should," not "must," and applies the same argument to two threads busy-waiting on each other's signals. The author concludes acquire/release is not inherently more deadlock-prone, while acknowledging the wording is weak and inviting contrary evidence.

### Source excerpt

I wasn't planning to write about lock-free programming again, but a commenter named Mike recently asked an interesting question on my Acquire and Release Semantics post from 2012. It's a question I wondered about years ago, but could never really reconcile until (possibly) now. A quick recap: A read-acquire operation cannot be reordered, either by the compiler or the CPU, with any read or write operation that follows it in program order. A write-release operation cannot be reordered with any read or write operation that precedes it in program order. Those rules don't prevent the reordering of a write-release followed by a read-acquire. For example, in C++, if A and B are std::atomic<int>, and we write: A.store(1, std::memory_order_release); int b = B.load(std::memory_order_acquire); ...the compiler is free to reorder those statements, as if we had written: int b = B.load(std::memory_order_acquire); A.store(1, std::memory_order_release); And that's fair. Why the heck not? On many architectures, including x86, the CPU could perform this reordering anyway. Well, here's where Mike's question comes in. What if A and B are spinlocks? Let's say that the spinlock is initially 0. To lock it, we repeatedly attempt a compare-and-swap, with acquire semantics, until it changes from 0 to 1. To unlock it, we simply set it back to 0, with release semantics. Now, suppose Thread 1 does the following: // Lock A int expected = 0; while (!A.compare_exchange_weak(expected, 1, std::memory_order_acquire)) { expected = 0; } // Unlock A A.store(0, std::memory_order_release); // Lock B while (!B.compare_exchange_weak(expected, 1, std::memory_order_acquire)) { expected = 0; } // Unlock B B.store(0, std::memory_order_release); Meanwhile, Thread 2 does the following: // Lock B int expected = 0; while (!B.compare_exchange_weak(expected, 1, std::memory_order_acquire)) { expected = 0; } // Lock A while (!A.compare_exchange_weak(expected, 1, std::memory_order_acquire)) { expected = 0; } // Unlock A A.

## Here's a Standalone Cairo DLL for Windows

DevFeed: [Here's a Standalone Cairo DLL for Windows](<https://devfeed.tech/articles/here-s-a-standalone-cairo-dll-for-windows-21010.md>)

Original publisher: [Read original article](<https://preshing.com/20170529/heres-a-standalone-cairo-dll-for-windows>)

Author: Jeff Preshing

Published: 2017-05-29T10:22:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [Library](<https://devfeed.tech/topics/library.md>), [C](<https://devfeed.tech/topics/c.md>), [Windows](<https://devfeed.tech/topics/windows.md>), [MSVC](<https://devfeed.tech/topics/msvc.md>), [CMake](<https://devfeed.tech/topics/cmake.md>), [GitHub](<https://devfeed.tech/topics/github.md>), [Open Source](<https://devfeed.tech/topics/open-source.md>), [x86](<https://devfeed.tech/topics/x86.md>), [Linux](<https://devfeed.tech/topics/linux.md>), [macOS](<https://devfeed.tech/topics/macos.md>)

Tags: [c](<https://devfeed.tech/tags/c.md>), [cmake](<https://devfeed.tech/tags/cmake.md>), [github](<https://devfeed.tech/tags/github.md>), [graphics](<https://devfeed.tech/tags/graphics.md>), [graphs](<https://devfeed.tech/tags/graphs.md>), [libraries](<https://devfeed.tech/tags/libraries.md>), [linux](<https://devfeed.tech/tags/linux.md>), [macos](<https://devfeed.tech/tags/macos.md>), [msvc](<https://devfeed.tech/tags/msvc.md>), [open-source](<https://devfeed.tech/tags/open-source.md>), [windows](<https://devfeed.tech/tags/windows.md>), [x86](<https://devfeed.tech/tags/x86.md>)

### AI overview

The article presents standalone Cairo DLLs for Windows, packaged with headers, import libraries, and x86/x64 binaries. The DLLs are statically linked, have no external dependencies, support MSVC applications, and use FreeType for text rendering. A GitHub build script and a CMake sample application are also provided.

### Source excerpt

Cairo is an open source C library for drawing vector graphics. I used it to create many of the diagrams and graphs on this blog. Cairo is great, but it's always been difficult to find a precompiled Windows DLL that's up-to-date and that doesn't depend on a bunch of other DLLs. I was recently unable to find such a DLL, so I wrote a script to simplify the build process for one. The script is shared on GitHub: If you just want a binary package, you can download one from the Releases page: The binary package contains Cairo header files, import libraries and DLLs for both x86 and x64. The DLLs are statically linked with their own C runtime and have no external dependencies. Since Cairo's API is pure C, these DLLs should work with any application built with any version of MSVC. I configured these DLLs to render text using FreeType because I find the quality of FreeType-rendered text better than Win32-rendered text, which Cairo normally uses by default. FreeType also supports more font formats and gives text a consistent appearance across different operating systems. Sample Application Using CMake Here's a small Cairo application to test the DLLs. It uses CMake to support multiple platforms including Windows, MacOS and Linux. Hope this helps somebody!

## Learn CMake's Scripting Language in 15 Minutes

DevFeed: [Learn CMake's Scripting Language in 15 Minutes](<https://devfeed.tech/articles/learn-cmake-s-scripting-language-in-15-minutes-21009.md>)

Original publisher: [Read original article](<https://preshing.com/20170522/learn-cmakes-scripting-language-in-15-minutes>)

Author: Jeff Preshing

Published: 2017-05-22T12:20:00Z

Content type: tutorial

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [CMake](<https://devfeed.tech/topics/cmake.md>), [Script](<https://devfeed.tech/topics/script.md>), [conditionals](<https://devfeed.tech/topics/conditionals.md>), [if statement](<https://devfeed.tech/topics/if-statement.md>)

Tags: [cmake](<https://devfeed.tech/tags/cmake.md>), [language](<https://devfeed.tech/tags/language.md>), [learn](<https://devfeed.tech/tags/learn.md>), [scripting](<https://devfeed.tech/tags/scripting.md>)

### AI overview

CMake scripts use commands whose arguments are strings; variables are strings too, and unquoted semicolon-delimited variable references can expand into multiple arguments. The guide demonstrates running a script with `cmake -P`, setting variables, flow control, lists, and target properties. Its key scope distinctions are practical: functions have their own scope and can set caller variables with `PARENT_SCOPE`; macros share the caller's scope; `include` and `find_package` scripts run in the caller's scope, while `add_subdirectory` runs a `CMakeLists.txt` in a new scope. Targets remain visible across scopes, and their properties feed build pipeline generation. The guide covers syntax and the programming model rather than all built-in commands, and says generator expressions are outside its coverage.

### Source excerpt

As explained in my previous post, every CMake-based project must contain a script named CMakeLists.txt. This script defines targets, but it can also do a lot of other things, such as finding third-party libraries or generating C++ header files. CMake scripts have a lot of flexibility. Every time you integrate an external library, and often when adding support for another platform, you'll need to edit the script. I spent a long time editing CMake scripts without really understanding the language, as the documentation is quite scattered, but eventually, things clicked. The goal of this post is to get you to the same point as quickly as possible. This post won't cover all of CMake's built-in commands, as there are hundreds, but it is a fairly complete guide to the syntax and programming model of the language. Hello World If you create a file named hello.txt with the following contents: message("Hello world!") # A message to print ...you can run it from the command line using cmake -P hello.txt. (The -P option runs the given script, but doesn't generate a build pipeline.) As expected, it prints "Hello world!". $ cmake -P hello.txt Hello world! All Variables Are Strings In CMake, every variable is a string. You can substitute a variable inside a string literal by surrounding it with ${}. This is called a variable reference. Modify hello.txt as follows: message("Hello ${NAME}!") # Substitute a variable into the message Now, if we define NAME on the cmake command line using the -D option, the script will use it: $ cmake -DNAME=Newman -P hello.txt Hello Newman! When a variable is undefined, it defaults to an empty string: $ cmake -P hello.txt Hello ! To define a variable inside a script, use the set command. The first argument is the name of the variable to assign, and the second argument is its value: set(THING "funk") message("We want the ${THING}!") Quotes around arguments are optional, as long as there are no spaces or variable references in the argument. For example, I c

## How to Build a CMake-Based Project

DevFeed: [How to Build a CMake-Based Project](<https://devfeed.tech/articles/how-to-build-a-cmake-based-project-21008.md>)

Original publisher: [Read original article](<https://preshing.com/20170511/how-to-build-a-cmake-based-project>)

Author: Jeff Preshing

Published: 2017-05-11T12:30:00Z

Content type: tutorial

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [CMake](<https://devfeed.tech/topics/cmake.md>), [Learning](<https://devfeed.tech/topics/learning.md>), [Cache](<https://devfeed.tech/topics/cache.md>), [make](<https://devfeed.tech/topics/make.md>)

Tags: [3d](<https://devfeed.tech/tags/3d.md>), [blender](<https://devfeed.tech/tags/blender.md>), [build](<https://devfeed.tech/tags/build.md>), [building](<https://devfeed.tech/tags/building.md>), [c](<https://devfeed.tech/tags/c.md>), [c-c-plus-plus](<https://devfeed.tech/tags/c-c-plus-plus.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [cmake](<https://devfeed.tech/tags/cmake.md>), [command-line](<https://devfeed.tech/tags/command-line.md>), [how-to](<https://devfeed.tech/tags/how-to.md>), [linux](<https://devfeed.tech/tags/linux.md>), [llvm](<https://devfeed.tech/tags/llvm.md>), [logo](<https://devfeed.tech/tags/logo.md>), [macos](<https://devfeed.tech/tags/macos.md>), [open-source](<https://devfeed.tech/tags/open-source.md>), [open-source-projects](<https://devfeed.tech/tags/open-source-projects.md>), [opengl](<https://devfeed.tech/tags/opengl.md>), [project](<https://devfeed.tech/tags/project.md>), [qt](<https://devfeed.tech/tags/qt.md>), [qt-creator](<https://devfeed.tech/tags/qt-creator.md>)

### AI overview

CMake reads a project's `CMakeLists.txt` during configuration, then generates a build pipeline in a separate binary folder. Keeping that folder apart from source makes it disposable and lets you maintain different configurations; its `CMakeCache.txt` stores generator choices and project options for later runs. The guide shows command-line, `cmake-gui` and `ccmake` configuration, then covers builds with Makefiles, Visual Studio, Xcode and Qt Creator. A key difference is that Makefiles and Ninja are single-configuration: set `CMAKE_BUILD_TYPE` (such as Debug or RelWithDebInfo), and regenerate to switch types. Visual Studio solutions support changing configurations in the IDE, while the Visual Studio 2017 folder workflow has limitations around source files, property pages and editing cache options. CMake can also build from the command line across generators, cross-compile with a toolchain file, and produce `compile_commands.json`.

### Source excerpt

CMake is a versatile tool that helps you build C/C++ projects on just about any platform you can think of. It's used by many popular open source projects including LLVM, Qt, KDE and Blender. All CMake-based projects contain a script named CMakeLists.txt, and this post is meant as a guide for configuring and building such projects. This post won't show you how to write a CMake script - that's getting ahead of things, in my opinion. As an example, I've prepared a CMake-based project that uses SDL2 and OpenGL to render a spinning 3D logo. You can build it on Windows, MacOS or Linux. The information here applies to any CMake-based project, so feel free to skip ahead to any section. However, I recommend reading the first two sections first. The Source and Binary Folders The Configure and Generate Steps Running CMake from the Command Line Running cmake-gui Running ccmake Building with Unix Makefiles Building with Visual Studio Building with Xcode Building with Qt Creator Other CMake Features If you don't have CMake yet, there are installers and binary distributions on the CMake website. In Unix-like environments, including Linux, it's usually available through the system package manager. You can also install it through MacPorts, Homebrew, Cygwin or MSYS2. The Source and Binary Folders CMake generates build pipelines. A build pipeline might be a Visual Studio .sln file, an Xcode .xcodeproj or a Unix-style Makefile. It can also take several other forms. To generate a build pipeline, CMake needs to know the source and binary folders. The source folder is the one containing CMakeLists.txt. The binary folder is where CMake generates the build pipeline. You can create the binary folder anywhere you want. A common practice is to create a subdirectory build beneath CMakeLists.txt. By keeping the binary folder separate from the source, you can delete the binary folder at any time to get back to a clean slate. You can even create several binary folders, side-by-side, that use diffe

## Using Quiescent States to Reclaim Memory

DevFeed: [Using Quiescent States to Reclaim Memory](<https://devfeed.tech/articles/using-quiescent-states-to-reclaim-memory-21007.md>)

Original publisher: [Read original article](<https://preshing.com/20160726/using-quiescent-states-to-reclaim-memory>)

Author: Jeff Preshing

Published: 2016-07-26T10:30:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [C++](<https://devfeed.tech/topics/c-plus-plus.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [Data structures](<https://devfeed.tech/topics/data-structures.md>), [Memory Leaks](<https://devfeed.tech/topics/memory-leaks.md>), [Scalability](<https://devfeed.tech/topics/scalability.md>), [Network](<https://devfeed.tech/topics/network.md>), [Server](<https://devfeed.tech/topics/server.md>)

Tags: [atomic](<https://devfeed.tech/tags/atomic.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [memory](<https://devfeed.tech/tags/memory.md>), [network](<https://devfeed.tech/tags/network.md>), [scalability](<https://devfeed.tech/tags/scalability.md>), [server](<https://devfeed.tech/tags/server.md>), [structure](<https://devfeed.tech/tags/structure.md>), [thread](<https://devfeed.tech/tags/thread.md>), [vector](<https://devfeed.tech/tags/vector.md>)

### AI overview

This article explains how to reclaim memory safely in a multithreaded C++ program by replacing a read-write-locked data structure with immutable copies referenced through an atomic pointer. It introduces quiescent states to determine when older copies are no longer in use and can be deleted, preserving scalability while avoiding memory leaks.

### Source excerpt

If you want to support multiple readers for a data structure, while protecting against concurrent writes, a read-write lock might seem like the only way - but it isn't! You can achieve the same thing without a read-write lock if you allow several copies of the data structure to exist in memory. You just need a way to delete old copies when they're no longer in use. Let's look at one way to achieve that in C++. We'll start with an example based on a read-write lock. Using a Read-Write Lock Suppose you have a network server with dozens of threads. Each thread broadcasts messages to dozens of connected clients. Once in a while, a new client connects or an existing client disconnects, so the list of connected clients must change. We can store the list of connected clients in a std::vector and protect it using a read-write lock such as std::shared_mutex. class Server { private: std::shared_mutex m_rwLock; // Read-write lock std::vector<int> m_clients; // List of connected clients public: void broadcast(const void* msg, size_t len) { std::shared_lock<std::shared_mutex> shared(m_rwLock); // Shared lock for (int fd : m_clients) send(fd, msg, len, 0); } void addClient(int fd) { std::unique_lock<std::shared_mutex> exclusive(m_rwLock); // Exclusive lock m_clients.push_back(fd); } ... The broadcast function reads from the list of connected clients, but doesn't modify it, so it takes a read lock (also known as a shared lock). addClient, on the other hand, needs to modify the list, so it takes a write lock (also known as an exclusive lock). That's all fine and dandy. Now let's eliminate the read-write lock by allowing multiple copies of the list to exist at the same time. Eliminating the Read-Write Lock First, we must establish an atomic pointer to the current list. This pointer will hold the most up-to-date list of connected clients at any moment in time. class Server { private: struct ClientList { std::vector<int> clients; }; std::atomic<ClientList*> m_currentList; // The most

## Leapfrog Probing

DevFeed: [Leapfrog Probing](<https://devfeed.tech/articles/leapfrog-probing-21006.md>)

Original publisher: [Read original article](<https://preshing.com/20160314/leapfrog-probing>)

Author: Jeff Preshing

Published: 2016-03-14T20:24:00Z

Content type: tutorial

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [hash collision](<https://devfeed.tech/topics/hash-collision.md>), [Cache](<https://devfeed.tech/topics/cache.md>)

Tags: [array](<https://devfeed.tech/tags/array.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [cells](<https://devfeed.tech/tags/cells.md>), [data-structure](<https://devfeed.tech/tags/data-structure.md>), [friendly](<https://devfeed.tech/tags/friendly.md>), [hash-table](<https://devfeed.tech/tags/hash-table.md>), [linear-probing](<https://devfeed.tech/tags/linear-probing.md>), [linked-list](<https://devfeed.tech/tags/linked-list.md>), [open-addressing](<https://devfeed.tech/tags/open-addressing.md>)

### AI overview

Leapfrog probing shortens average searches versus linear probing and supports concurrent hash maps by storing two one-byte deltas per cell to link each bucket's probe chain. Lookups check the ideal cell, follow its first delta to the chain, then use the second delta until it is zero. Insertions search the chain, linearly find a free cell, and link it; if the required delta exceeds one byte, the table must be migrated. In Junction's concurrent Leapfrog map, cells are reserved with compare-and-swap and linked with a separate relaxed atomic store, so operations handle intermediate visibility states. Racing gets may return "not found," while concurrent inserts spin until a possibly linked key is visible or repair a missing link when they encounter an unexpected same-bucket item. The excerpt reports Leapfrog was the fastest concurrent map tested up to a modest number of CPU cores, and attributes performance in part to low write contention; it gives no benchmark figures.

### Source excerpt

A hash table is a data structure that stores a set of items, each of which maps a specific key to a specific value. There are many ways to implement a hash table, but they all have one thing in common: buckets. Every hash table maintains an array of buckets somewhere, and each item belongs to exactly one bucket. To determine the bucket for a given item, you typically hash the item's key, then compute its modulus - that is, the remainder when divided by the number of buckets. For a hash table with 16 buckets, the modulus is given by the final hexadecimal digit of the hash. Inevitably, several items will end up belonging to same bucket. For simplicity, let's suppose the hash function is invertible, so that we only need to store hashed keys. A well-known strategy is to store the bucket contents in a linked list: This strategy is known as separate chaining. Separate chaining tends to be relatively slow on modern CPUs, since it requires a lot of pointer lookups. I'm more fond of open addressing, which stores all the items in the array itself: In open addressing, each cell in the array still represents a single bucket, but can actually store an item belonging to any bucket. Open addressing is more cache-friendly than separate chaining. If an item is not found in its ideal cell, it's often nearby. The drawback is that as the array becomes full, you may need to search a lot of cells before finding a particular item, depending on the probing strategy. For example, consider linear probing, the simplest probing strategy. Suppose we want to insert the item (13, "orange") into the above table, and the hash of 13 is 0x95bb7d92. Ideally, we'd store this item at index 2, the last hexadecimal digit of the hash, but that cell is already taken. Under linear probing, we find the next free cell by searching linearly, starting at the item's ideal index, and store the item there instead: As you can see, the item (13, "orange") ended up quite far from its ideal cell. Not great for lookups.

## A Resizable Concurrent Map

DevFeed: [A Resizable Concurrent Map](<https://devfeed.tech/articles/a-resizable-concurrent-map-21005.md>)

Original publisher: [Read original article](<https://preshing.com/20160222/a-resizable-concurrent-map>)

Author: Jeff Preshing

Published: 2016-02-22T13:05:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [race-condition](<https://devfeed.tech/topics/race-condition.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [synchronization](<https://devfeed.tech/topics/synchronization.md>)

Tags: [blocking](<https://devfeed.tech/tags/blocking.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [delete](<https://devfeed.tech/tags/delete.md>), [hash](<https://devfeed.tech/tags/hash.md>), [hash-table](<https://devfeed.tech/tags/hash-table.md>), [java](<https://devfeed.tech/tags/java.md>), [linear-probing](<https://devfeed.tech/tags/linear-probing.md>), [lock-free](<https://devfeed.tech/tags/lock-free.md>), [map](<https://devfeed.tech/tags/map.md>), [maps](<https://devfeed.tech/tags/maps.md>), [migration](<https://devfeed.tech/tags/migration.md>), [open-addressing](<https://devfeed.tech/tags/open-addressing.md>), [resize](<https://devfeed.tech/tags/resize.md>), [table](<https://devfeed.tech/tags/table.md>), [thread](<https://devfeed.tech/tags/thread.md>)

### AI overview

Junction's Linear map extends the simpler Crude map with resizing and deletion while permitting concurrent operations. It uses open addressing and linear probing, but stores hashed keys and keeps the table, size mask, and remaining-cell counter behind one root pointer. When the counter signals overpopulation, migration copies entries into a larger table. To avoid losing concurrent updates, migration replaces old cell values with Redirect markers using compare-and-swap; operations that encounter a marker are directed to the new table. In the version described, concurrent assignments cannot modify the new table until migration finishes, and gets that encounter Redirect help complete migration rather than immediately reading from the new table. Erase marks a value as NullValue but retains its hash, so deleted cells are reclaimed during migration. The excerpt says the invertible hash limits supported keys to integers and raw pointers.

### Source excerpt

In an earlier post, I showed how to implement the "world's simplest lock-free hash table" in C++. It was so simple that you couldn't even delete entries or resize the table. Well, a few years have passed since then, and I've recently written some concurrent maps without those limitations. You'll find them in my Junction project on GitHub. Junction contains several concurrent maps - even the 'world's simplest' is there, under the name ConcurrentMap_Crude. For brevity, let's call that one the Crude map. In this post, I'll explain the difference between the Crude map and Junction's Linear map. Linear is the simplest Junction map that supports both resize and delete. You can review the original post for an explanation of how the Crude map works. To recap: It's based on open addressing and linear probing. That means it's basically a big array of keys and values using a linear search. When inserting or looking up a given key, you hash the key to determine where to begin the search. Concurrent inserts and lookups are permitted. Junction's Linear map is based on the same principle, except that when the array gets too full, its entire contents are migrated to a new, larger array. When the migration completes, the old table is replaced with the old one. So, how do we achieve that while still allowing concurrent operations? The Linear map's approach is based on Cliff Click's non-blocking hash map in Java, but has a few differences. The Data Structure First, we need to modify our data structure a little bit. The original Crude map had two data members: A pointer m_cells and an integer m_sizeMask. The Linear map instead has a single data member m_root, which points to a Table structure followed by the cells themselves in a single, contiguous memory block. In the Table structure, there's a new shared counter cellsRemaining, initially set to 75% of the table size. Whenever a thread tries to insert a new key, it decrements cellsRemaining first. If it decrements cellsRemaining below

## New Concurrent Hash Maps for C++

DevFeed: [New Concurrent Hash Maps for C++](<https://devfeed.tech/articles/new-concurrent-hash-maps-for-c-21004.md>)

Original publisher: [Read original article](<https://preshing.com/20160201/new-concurrent-hash-maps-for-cpp>)

Author: Jeff Preshing

Published: 2016-02-01T13:30:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [synchronization](<https://devfeed.tech/topics/synchronization.md>), [Open Source](<https://devfeed.tech/topics/open-source.md>), [locking](<https://devfeed.tech/topics/locking.md>), [CMake](<https://devfeed.tech/topics/cmake.md>)

Tags: [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [hash](<https://devfeed.tech/tags/hash.md>), [hash-table](<https://devfeed.tech/tags/hash-table.md>), [maps](<https://devfeed.tech/tags/maps.md>)

### AI overview

Junction is a BSD-licensed C++ library offering three concurrent hash maps whose operations can be called atomically across threads. Linear supports resizing and deletion; Leapfrog uses a hopscotch-inspired probing strategy that improves lookup in densely populated tables and scales better by modifying shared state less often; Grampa splits highly populated maps into smaller fixed-size Leapfrog tables. The author reports that Junction's two fastest maps outperformed other concurrent maps on a Core i7-5930K. Maps reserve null keys and special values, and all rely on QSBR: each thread must periodically report a quiescent state. Object lifetimes still require user management, and smart pointers are not supported. Tested platforms listed are Windows, Ubuntu, OS X, and iOS. The author labels the software experimental and alpha, despite passing their tests.

### Source excerpt

A map is a data structure that maps a collection of keys to a collection of values. It's a common concept in computer programming. You typically manipulate maps using functions such as find, insert and erase. A concurrent map is one that lets you call some of those functions concurrently - even in combinations where the map is modified. If it lets you call insert from multiple threads, with no mutual exclusion, it's a concurrent map. If it lets you call insert while another thread is calling find, with no mutual exclusion, it's a concurrent map. Other combinations might be allowed, too. Traditional maps, such as std::map and std::unordered_map, don't allow that. Today I'm releasing Junction, a C++ library that contains several new concurrent maps. It's BSD-licensed, so you can use the source code freely in any project, for any purpose. On my Core i7-5930K, Junction's two fastest maps outperform all other concurrent maps. They come in three flavors: Junction's Linear map is similar to the simple lock-free hash table I published a while ago, except that it also supports resizing, deleting entries, and templated key/value types. It was inspired by Cliff Click's non-blocking hash map in Java, but has a few differences. Junction's Leapfrog map is similar to Linear, except that it uses a probing strategy loosely based on hopscotch hashing. This strategy improves lookup efficiency when the table is densely populated. Leapfrog scales better than Linear because it modifies shared state far less frequently. Junction's Grampa map is similar to Leapfrog, except that at high populations, the map gets split into a set of smaller, fixed-size Leapfrog tables. Whenever one of those tables overflows, it gets split into two new tables instead of resizing the entire map. Junction aims to support as many platforms as possible. So far, it's been tested on Windows, Ubuntu, OS X and iOS. Its main dependencies are CMake and a companion library called Turf. Turf is an abstraction layer over

## You Can Do Any Kind of Atomic Read-Modify-Write Operation

DevFeed: [You Can Do Any Kind of Atomic Read-Modify-Write Operation](<https://devfeed.tech/articles/you-can-do-any-kind-of-atomic-read-modify-write-operation-21003.md>)

Original publisher: [Read original article](<https://preshing.com/20150402/you-can-do-any-kind-of-atomic-read-modify-write-operation>)

Author: Jeff Preshing

Published: 2015-04-02T11:20:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>)

Tags: [algorithm](<https://devfeed.tech/tags/algorithm.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [atomics](<https://devfeed.tech/tags/atomics.md>), [cas](<https://devfeed.tech/tags/cas.md>), [clang](<https://devfeed.tech/tags/clang.md>), [compiler](<https://devfeed.tech/tags/compiler.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [concurrently](<https://devfeed.tech/tags/concurrently.md>), [lock-free](<https://devfeed.tech/tags/lock-free.md>), [memory](<https://devfeed.tech/tags/memory.md>), [mutex](<https://devfeed.tech/tags/mutex.md>), [operations](<https://devfeed.tech/tags/operations.md>)

### AI overview

C++11's `compare_exchange_weak` can implement custom atomic read-modify-write operations through a compare-and-swap loop: compute a new value, retry if another thread changed the shared value, and stop when the update succeeds or a condition makes it a no-op. The article demonstrates multiplication, a conditional decrement-or-halving operation, and updating two values packed into one atomic object. Such loops are atomic; they are lock-free only when the compare-and-swap implementation is lock-free, and weak compare-exchange may fail spuriously. The C++11 standard does not guarantee every atomic type is lock-free, so compiler and target support matter. Packing data into an integer atomic may help, but memory-ordering guarantees still need consideration, especially when passing non-atomic data between threads.

### Source excerpt

Atomic read-modify-write operations - or "RMWs" - are more sophisticated than atomic loads and stores. They let you read from a variable in shared memory and simultaneously write a different value in its place. In the C++11 atomic library, all of the following functions perform an RMW: std::atomic<>::fetch_add() std::atomic<>::fetch_sub() std::atomic<>::fetch_and() std::atomic<>::fetch_or() std::atomic<>::fetch_xor() std::atomic<>::exchange() std::atomic<>::compare_exchange_strong() std::atomic<>::compare_exchange_weak() fetch_add, for example, reads from a shared variable, adds another value to it, and writes the result back - all in one indivisible step. You can accomplish the same thing using a mutex, but a mutex-based version wouldn't be lock-free. RMW operations, on the other hand, are designed to be lock-free. They'll take advantage of lock-free CPU instructions whenever possible, such as ldrex/strex on ARMv7. A novice programmer might look at the above list of functions and ask, "Why does C++11 offer so few RMW operations? Why is there an atomic fetch_add, but no atomic fetch_multiply, no fetch_divide and no fetch_shift_left?" There are two reasons: Because there is very little need for those RMW operations in practice. Try not to get the wrong impression of how RMWs are used. You can't write safe multithreaded code by taking a single-threaded algorithm and turning each step into an RMW. Because if you do need those operations, you can easily implement them yourself. As the title says, you can do any kind of RMW operation! Compare-and-Swap: The Mother of All RMWs Out of all the available RMW operations in C++11, the only one that is absolutely essential is compare_exchange_weak. Every other RMW operation can be implemented using that one. It takes a minimum of two arguments: shared.compare_exchange_weak(T& expected, T desired, ...); This function attempts to store the desired value to shared, but only if the current value of shared matches expected. It return

## Safe Bitfields in C++

DevFeed: [Safe Bitfields in C++](<https://devfeed.tech/articles/safe-bitfields-in-c-21002.md>)

Original publisher: [Read original article](<https://preshing.com/20150324/safe-bitfields-in-cpp>)

Author: Jeff Preshing

Published: 2015-03-24T10:15:00Z

Content type: tutorial

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [c/c++](<https://devfeed.tech/topics/c-c-plus-plus.md>), [typesafety](<https://devfeed.tech/topics/typesafety.md>), [software-development](<https://devfeed.tech/topics/software-development.md>), [debugging](<https://devfeed.tech/topics/debugging.md>), [atomic reference counting](<https://devfeed.tech/topics/atomic-reference-counting.md>)

Tags: [array](<https://devfeed.tech/tags/array.md>), [arrays](<https://devfeed.tech/tags/arrays.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [behavior](<https://devfeed.tech/tags/behavior.md>), [bits](<https://devfeed.tech/tags/bits.md>), [build](<https://devfeed.tech/tags/build.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [clang](<https://devfeed.tech/tags/clang.md>), [classes](<https://devfeed.tech/tags/classes.md>), [code](<https://devfeed.tech/tags/code.md>), [constructor](<https://devfeed.tech/tags/constructor.md>), [debug](<https://devfeed.tech/tags/debug.md>), [errors](<https://devfeed.tech/tags/errors.md>), [github](<https://devfeed.tech/tags/github.md>), [macros](<https://devfeed.tech/tags/macros.md>), [members](<https://devfeed.tech/tags/members.md>), [runtime](<https://devfeed.tech/tags/runtime.md>), [safety](<https://devfeed.tech/tags/safety.md>), [status](<https://devfeed.tech/tags/status.md>), [templating](<https://devfeed.tech/tags/templating.md>)

### AI overview

The author presents a C++ template-and-macro bitfield that packs three 10-bit fields into a 32-bit value. It supports ordinary assignment and reads; with assertions enabled, out-of-range assignments, increment overflow, decrement underflow, and packed-array index errors trigger runtime asserts. The type converts to its underlying integer, allowing use with C++11 atomic operations; helper values support atomic fetch_add on a field. A separate macro supports indexed packed arrays, such as eight 4-bit elements. The implementation overlays standard-layout members in a union, and the author argues that the common initial sequence makes the accesses permitted by the cited C++ standard rule. The author reports that optimized MSVC, GCC, and Clang builds inline the operations to code as efficient as explicit bit twiddling. Silent wraparound is mentioned as possible but not implemented; the convenience comes with increased obfuscation.

### Source excerpt

In my cpp11-on-multicore project on GitHub, there's a class that packs three 10-bit values into a 32-bit integer. I could have implemented it using traditional bitfields... struct Status { uint32_t readers : 10; uint32_t waitToRead : 10; uint32_t writers : 10; }; Or with some bit twiddling... uint32_t status = readers | (waitToRead << 10) | (writers << 20); Instead, I did what any overzealous C++ programmer does. I abused the preprocessor and templating system. BEGIN_BITFIELD_TYPE(Status, uint32_t) // type name, storage size ADD_BITFIELD_MEMBER(readers, 0, 10) // member name, offset, number of bits ADD_BITFIELD_MEMBER(waitToRead, 10, 10) ADD_BITFIELD_MEMBER(writers, 20, 10) END_BITFIELD_TYPE() The above set of macros defines a new bitfield type Status with three members. The second argument to BEGIN_BITFIELD_TYPE() must be an unsigned integer type. The second argument to ADD_BITFIELD_MEMBER() specifies each member's offset, while the third argument specifies the number of bits. I call this a safe bitfield because it performs safety checks to ensure that every operation on the bitfield fits within the available number of bits. It also supports packed arrays. I thought the technique deserved a quick explanation here, since I'm going to refer back to it in future posts. How to Manipulate a Safe Bitfield Let's take Status as an example. Simply create an object of type Status as you would any other object. By default, it's initialized to zero, but you can initialize it from any integer of the same size. In the GitHub project, it's often initialized from the result of a C++11 atomic operation. Status status = m_status.load(std::memory_order_relaxed); Setting the value of a bitfield member is easy. Just assign to the member the same way you would using a traditional bitfield. If asserts are enabled - such as in a debug build - and you try to assign a value that's too large for the bitfield, an assert will occur at runtime. It's meant to help catch programming errors during dev

## Semaphores are Surprisingly Versatile

DevFeed: [Semaphores are Surprisingly Versatile](<https://devfeed.tech/articles/semaphores-are-surprisingly-versatile-21001.md>)

Original publisher: [Read original article](<https://preshing.com/20150316/semaphores-are-surprisingly-versatile>)

Author: Jeff Preshing

Published: 2015-03-16T09:50:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [locking](<https://devfeed.tech/topics/locking.md>), [Deadlock](<https://devfeed.tech/topics/deadlock.md>)

Tags: [atomic](<https://devfeed.tech/tags/atomic.md>), [class](<https://devfeed.tech/tags/class.md>), [cpu](<https://devfeed.tech/tags/cpu.md>), [cpu-time](<https://devfeed.tech/tags/cpu-time.md>), [dijkstra](<https://devfeed.tech/tags/dijkstra.md>), [dining](<https://devfeed.tech/tags/dining.md>), [environments](<https://devfeed.tech/tags/environments.md>), [event](<https://devfeed.tech/tags/event.md>), [exclusive](<https://devfeed.tech/tags/exclusive.md>), [github](<https://devfeed.tech/tags/github.md>), [implement](<https://devfeed.tech/tags/implement.md>), [ios](<https://devfeed.tech/tags/ios.md>), [kernel](<https://devfeed.tech/tags/kernel.md>), [library](<https://devfeed.tech/tags/library.md>), [lightweight](<https://devfeed.tech/tags/lightweight.md>), [like](<https://devfeed.tech/tags/like.md>), [linux](<https://devfeed.tech/tags/linux.md>), [lock](<https://devfeed.tech/tags/lock.md>), [macos](<https://devfeed.tech/tags/macos.md>), [versatile](<https://devfeed.tech/tags/versatile.md>)

### AI overview

The article shows how semaphores and atomic operations can implement several lightweight C++11 synchronization primitives through a "box office/bouncer" pattern: atomics track state and decide whether threads proceed or wait, while a semaphore queues and releases waiters. Examples include a mutex, auto-reset event, read-write lock, dining philosophers solution, and a semaphore with partial spinning. The implementations can avoid kernel calls when uncontended; the lightweight semaphore can spin briefly before sleeping. A portable Semaphore class maps to native semaphores on several platforms. The author reports that, on one Windows PC, an auto-reset event was 10x faster than a condition-variable version and the test suite benefited significantly from partial spinning, while noting the fixed 10,000-iteration spin strategy may not suit every environment. The article also acknowledges that conventional mutex and condition-variable approaches are often preferred because semaphore techniques can be error prone.

### Source excerpt

In multithreaded programming, it's important to make threads wait. They must wait for exclusive access to a resource. They must wait when there's no work available. One way to make threads wait - and put them to sleep inside the kernel, so that they no longer take any CPU time - is with a semaphore. I used to think semaphores were strange and old-fashioned. They were invented by Edsger Dijkstra back in the early 1960s, before anyone had done much multithreaded programming, or much programming at all, for that matter. I knew that a semaphore could keep track of available units of a resource, or function as a clunky kind of mutex, but that seemed to be about it. My opinion changed once I realized that, using only semaphores and atomic operations, it's possible to implement all of the following primitives: A Lightweight Mutex A Lightweight Auto-Reset Event Object A Lightweight Read-Write Lock Another Solution to the Dining Philosophers Problem A Lightweight Semaphore With Partial Spinning Not only that, but these implementations share some desirable properties. They're lightweight, in the sense that some operations happen entirely in userspace, and they can (optionally) spin for a short period before sleeping in the kernel. You'll find all of the C++11 source code on GitHub. Since the standard C++11 library does not include semaphores, I've also provided a portable Semaphore class that maps directly to native semaphores on Windows, MacOS, iOS, Linux and other POSIX environments. You should be able to drop any of these primitives into almost any existing C++11 project. A Semaphore Is Like a Bouncer Imagine a set of waiting threads, lined up in a queue - much like a lineup in front of a busy nightclub or theatre. A semaphore is like a bouncer at the front of the lineup. He only allows threads to proceed when instructed to do so. Each thread decides for itself when to join the queue. Dijkstra called this the P operation. P originally stood for some funny-sounding Dutch wo

## C++ Has Become More Pythonic

DevFeed: [C++ Has Become More Pythonic](<https://devfeed.tech/articles/c-has-become-more-pythonic-21000.md>)

Original publisher: [Read original article](<https://preshing.com/20141202/cpp-has-become-more-pythonic>)

Author: Jeff Preshing

Published: 2014-12-02T13:20:00Z

Content type: comparison

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [c/c++](<https://devfeed.tech/topics/c-c-plus-plus.md>), [Python](<https://devfeed.tech/topics/python.md>), [Functional programming](<https://devfeed.tech/topics/functional-programming.md>), [Closure](<https://devfeed.tech/topics/closure.md>)

Tags: [algorithms](<https://devfeed.tech/tags/algorithms.md>), [arguments](<https://devfeed.tech/tags/arguments.md>), [bjarne-stroustrup](<https://devfeed.tech/tags/bjarne-stroustrup.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [capture](<https://devfeed.tech/tags/capture.md>), [class](<https://devfeed.tech/tags/class.md>), [compile](<https://devfeed.tech/tags/compile.md>), [gcc](<https://devfeed.tech/tags/gcc.md>), [lambda](<https://devfeed.tech/tags/lambda.md>), [literals](<https://devfeed.tech/tags/literals.md>), [loops](<https://devfeed.tech/tags/loops.md>), [map](<https://devfeed.tech/tags/map.md>), [python](<https://devfeed.tech/tags/python.md>), [string](<https://devfeed.tech/tags/string.md>), [types](<https://devfeed.tech/tags/types.md>), [vector](<https://devfeed.tech/tags/vector.md>), [windows](<https://devfeed.tech/tags/windows.md>)

### AI overview

The excerpt's takeaway is that C++11 and C++14 add constructs that give C++ a more Python-like style, while retaining static typing. Examples include binary and raw string literals, range-based loops over containers with begin/end, auto type deduction, tuples and unpacking with std::tie, initializer syntax for vectors and maps, and lambdas with captures. C++11 algorithms such as std::copy_if offer functional-style operations; the article also names transform, any_of, all_of, min, and max. C++ parameter packs support variable argument sequences, but unlike Python's *args, they are manipulated at compile time through templates rather than exposed as a runtime object. The author presents these parallels as similarities, not proof that Python directly influenced the changes. The supplied text is an excerpt and ends partway through the discussion.

### Source excerpt

C++ has changed a lot in recent years. The last two revisions, C++11 and C++14, introduce so many new features that, in the words of Bjarne Stroustrup, "It feels like a new language." It's true. Modern C++ lends itself to a whole new style of programming - and I couldn't help noticing it has more of a Python flavor. Ranged-based for loops, type deduction, vector and map initializers, lambda expressions. The more you explore modern C++, the more you find Python's fingerprints all over it. Was Python a direct influence on modern C++? Or did Python simply adopt a few useful constructs before C++ got around to it? You be the judge. Literals Python introduced binary literals in 2008. Now C++14 has them. [Update: Thiago Macieira points out in the comments that GCC actually supported them back in 2007.] static const int primes = 0b10100000100010100010100010101100; Python also introduced raw string literals back in 1998. They're convenient when hardcoding a regular expression or a Windows path. C++11 added the same idea with a slightly different syntax: const char* path = R"(c:\this\string\has\backslashes)"; Range-Based For Loops In Python, a for loop always iterates over a Python object: for x in myList: print(x) Meanwhile, for nearly three decades, C++ supported only C-style for loops. Finally, in C++11, range-based for loops were added: for (int x : myList) std::cout << x; You can iterate over a std::vector or any class which implements the begin and end member functions - not unlike Python's iterator protocol. With range-based for loops, I often find myself wishing C++ had Python's xrange function built-in. Auto Python has always been a dynamically typed language. You don't need to declare variable types anywhere, since types are a property of the objects themselves. x = "Hello world!" print(x) C++, on the other hand, is not dynamically typed. It's statically typed. But since C++11 repurposed the auto keyword for type deduction, you can write code that looks a lot like

## Fixing GCC's Implementation of memory\_order\_consume

DevFeed: [Fixing GCC's Implementation of memory\_order\_consume](<https://devfeed.tech/articles/fixing-gcc-s-implementation-of-memory-order-consume-20999.md>)

Original publisher: [Read original article](<https://preshing.com/20141124/fixing-gccs-implementation-of-memory_order_consume>)

Author: Jeff Preshing

Published: 2014-11-24T11:25:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [gcc](<https://devfeed.tech/topics/gcc.md>), [Compiler](<https://devfeed.tech/topics/compiler.md>), [bug](<https://devfeed.tech/topics/bug.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [Arm](<https://devfeed.tech/topics/arm.md>)

Tags: [arm](<https://devfeed.tech/tags/arm.md>), [bug](<https://devfeed.tech/tags/bug.md>), [building](<https://devfeed.tech/tags/building.md>), [compiler](<https://devfeed.tech/tags/compiler.md>), [cppcon](<https://devfeed.tech/tags/cppcon.md>), [gcc](<https://devfeed.tech/tags/gcc.md>), [process](<https://devfeed.tech/tags/process.md>), [processors](<https://devfeed.tech/tags/processors.md>), [thread](<https://devfeed.tech/tags/thread.md>)

### AI overview

This article examines a bug in GCC 4.9.2's implementation of C++11 memory_order_consume. It explains the expected ordering guarantees, demonstrates the bug with a multithreaded example, and documents verifying and patching the compiler while building an AArch64 cross-compiler.

### Source excerpt

As I explained previously, there are two valid ways for a C++11 compiler to implement memory_order_consume: an efficient strategy and a heavy one. In the heavy strategy, the compiler simply treats memory_order_consume as an alias for memory_order_acquire. The heavy strategy is not what the designers of memory_order_consume had in mind, but technically, it's still compliant with the C++11 standard. There's a somewhat common misconception that all current C++11 compilers use the heavy strategy. I certainly had that impression until recently, and others I spoke to at CppCon 2014 seemed to have that impression as well. This belief turns out not to be true: GCC does not always use the heavy strategy (yet). GCC 4.9.2 actually has a bug in its implementation of memory_order_consume, as described in this GCC bug report. I was rather surprised to learn that, since it contradicted my own experience with GCC 4.8.3, in which the PowerPC compiler appeared to use the heavy strategy correctly. I decided to verify the bug on my own, which is why I recently took an interest in building GCC cross-compilers. This post will explain the bug and document the process of patching the compiler. An Example That Illustrates the Compiler Bug Imagine a bunch of threads repeatedly calling the following read function: #include <atomic> std::atomic<int> Guard(0); int Payload[1] = { 0xbadf00d }; int read() { int f = Guard.load(std::memory_order_consume); // load-consume if (f != 0) return Payload[f - f]; // plain load from Payload[f - f] return 0; } At some point, another thread comes along and calls write: int write() { Payload[0] = 42; // plain store to Payload[0] Guard.store(1, std::memory_order_release); // store-release } If the compiler is fully compliant with the current C++11 standard, then there are only two possible return values from read: 0 or 42. The outcome depends on the value seen by the load-consume highlighted above. If the load-consume sees 0, then obviously, read will return 0.

## How to Build a GCC Cross-Compiler

DevFeed: [How to Build a GCC Cross-Compiler](<https://devfeed.tech/articles/how-to-build-a-gcc-cross-compiler-20998.md>)

Original publisher: [Read original article](<https://preshing.com/20141119/how-to-build-a-gcc-cross-compiler>)

Author: Jeff Preshing

Published: 2014-11-19T11:30:00Z

Content type: tutorial

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [Compiler](<https://devfeed.tech/topics/compiler.md>), [gcc](<https://devfeed.tech/topics/gcc.md>), [C++](<https://devfeed.tech/topics/c-plus-plus.md>), [Arm](<https://devfeed.tech/topics/arm.md>), [Debian](<https://devfeed.tech/topics/debian.md>), [Linux](<https://devfeed.tech/topics/linux.md>), [make](<https://devfeed.tech/topics/make.md>), [Open Source](<https://devfeed.tech/topics/open-source.md>), [apt](<https://devfeed.tech/topics/apt.md>)

Tags: [apt](<https://devfeed.tech/tags/apt.md>), [arm](<https://devfeed.tech/tags/arm.md>), [build](<https://devfeed.tech/tags/build.md>), [built-from-source](<https://devfeed.tech/tags/built-from-source.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [compiler](<https://devfeed.tech/tags/compiler.md>), [debian](<https://devfeed.tech/tags/debian.md>), [gcc](<https://devfeed.tech/tags/gcc.md>), [how-to](<https://devfeed.tech/tags/how-to.md>), [kernel](<https://devfeed.tech/tags/kernel.md>), [linux](<https://devfeed.tech/tags/linux.md>), [linux-kernel](<https://devfeed.tech/tags/linux-kernel.md>), [make](<https://devfeed.tech/tags/make.md>), [open-source](<https://devfeed.tech/tags/open-source.md>), [source](<https://devfeed.tech/tags/source.md>)

### AI overview

A practical guide to building a GCC cross-compiler on Debian Linux for generating C++ programs targeting the 64-bit AArch64 architecture. It explains the required packages, source downloads, build components, and how the resulting compiler, libraries, assembler, linker, and Linux kernel interfaces fit together.

### Source excerpt

GCC is not just a compiler. It's an open source project that lets you build all kinds of compilers. Some compilers support multithreading; some support shared libraries; some support multilib. It all depends on how you configure the compiler before building it. This guide will demonstrate how to build a cross-compiler, which is a compiler that builds programs for another machine. All you need is a Unix-like environment with a recent version of GCC already installed. In this guide, I'll use Debian Linux to build a full C++ cross-compiler for AArch64, a 64-bit instruction set available in the latest ARM processors. I don't actually own an AArch64 device - I just wanted an AArch64 compiler to verify this bug. Required Packages Starting with a clean Debian system, you must first install a few packages: $ sudo apt-get install g++ make gawk Everything else will be built from source. Create a new directory somewhere, and download the following source packages. (If you're following this guide at a later date, there will be more recent releases of each package available. Check for newer releases by pasting each URL into your browser without the filename. For example: http://ftpmirror.gnu.org/binutils/) $ wget http://ftpmirror.gnu.org/binutils/binutils-2.24.tar.gz $ wget http://ftpmirror.gnu.org/gcc/gcc-4.9.2/gcc-4.9.2.tar.gz $ wget https://www.kernel.org/pub/linux/kernel/v3.x/linux-3.17.2.tar.xz $ wget http://ftpmirror.gnu.org/glibc/glibc-2.20.tar.xz $ wget http://ftpmirror.gnu.org/mpfr/mpfr-3.1.2.tar.xz $ wget http://ftpmirror.gnu.org/gmp/gmp-6.0.0a.tar.xz $ wget http://ftpmirror.gnu.org/mpc/mpc-1.0.2.tar.gz $ wget ftp://gcc.gnu.org/pub/gcc/infrastructure/isl-0.12.2.tar.bz2 $ wget ftp://gcc.gnu.org/pub/gcc/infrastructure/cloog-0.18.1.tar.gz The first four packages - Binutils, GCC, the Linux kernel and Glibc - are the main ones. We could have installed the next three packages in binary form using our system's package manager instead, but that tends to provide older versions.

## How to Install the Latest GCC on Windows

DevFeed: [How to Install the Latest GCC on Windows](<https://devfeed.tech/articles/how-to-install-the-latest-gcc-on-windows-20997.md>)

Original publisher: [Read original article](<https://preshing.com/20141108/how-to-install-the-latest-gcc-on-windows>)

Author: Jeff Preshing

Published: 2014-11-08T15:50:00Z

Content type: tutorial

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [Learning](<https://devfeed.tech/topics/learning.md>), [Windows](<https://devfeed.tech/topics/windows.md>), [Jule](<https://devfeed.tech/topics/jule.md>)

Tags: [64-bit](<https://devfeed.tech/tags/64-bit.md>), [also](<https://devfeed.tech/tags/also.md>), [build](<https://devfeed.tech/tags/build.md>), [building](<https://devfeed.tech/tags/building.md>), [but](<https://devfeed.tech/tags/but.md>), [c](<https://devfeed.tech/tags/c.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [can](<https://devfeed.tech/tags/can.md>), [clang](<https://devfeed.tech/tags/clang.md>), [code](<https://devfeed.tech/tags/code.md>), [command](<https://devfeed.tech/tags/command.md>), [command-line](<https://devfeed.tech/tags/command-line.md>), [compile](<https://devfeed.tech/tags/compile.md>), [compiler](<https://devfeed.tech/tags/compiler.md>), [gcc](<https://devfeed.tech/tags/gcc.md>), [how-to](<https://devfeed.tech/tags/how-to.md>), [install](<https://devfeed.tech/tags/install.md>), [latest](<https://devfeed.tech/tags/latest.md>), [the-latest](<https://devfeed.tech/tags/the-latest.md>), [windows](<https://devfeed.tech/tags/windows.md>)

### AI overview

The guide builds GCC 4.9.2 on Windows inside Cygwin so C++14 generic lambdas can be compiled even when Cygwin's system GCC is older than 4.9. It installs build dependencies, configures an out-of-source build for C and C++ only, disables bootstrap and shared libraries to reduce build time and avoid DLL conflicts, then runs `make` and `make install`. The versioned executable (`g++-4.9.2`) can coexist with the system compiler and is tested with `-std=c++14`. The build reuses Cygwin's Binutils and C library, omits Graphite optimizations, and may require rerunning `make` if a parallel build segfaults. The text also notes MinGW-w64 as a native GCC option that avoids Cygwin.

### Source excerpt

Several modern C++ features are currently missing from Visual Studio Express, and from the system GCC compiler provided with many of today's Linux distributions. Generic lambdas - also known as polymorphic lambdas - are one such feature. This feature is, however, available in the latest versions of GCC and Clang. The following guide will help you install the latest GCC on Windows, so you can experiment with generic lambdas and other cutting-edge C++ features. You'll need to compile GCC from sources, but that's not a problem. Depending on the speed of your machine, you can have the latest GCC up and running in as little as 15 minutes. The steps are: Install Cygwin, which gives us a Unix-like environment running on Windows. Install a set of Cygwin packages required for building GCC. From within Cygwin, download the GCC source code, build and install it. Test the new GCC compiler in C++14 mode using the -std=c++14 option. [Update: As a commenter points out, you can also install native GCC compilers from the MinGW-w64 project without needing Cygwin.] 1. Install Cygwin First, download and run either the 32- or 64-bit version of the Cygwin installer, depending on your version of Windows. Cygwin's setup wizard will walk you through a series of steps. If your machine is located behind a proxy server, make sure to check "Use Internet Explorer Proxy Settings" when you get to the "Select Your Internet Connection" step. When you reach the "Select Packages" step (shown below), don't bother selecting any packages yet. Just go ahead and click Next. We'll add additional packages from the command line later. After the Cygwin installer completes, it's very important to keep the installer around. The installer is an executable named either setup-x86.exe or setup-x86_64.exe, and you'll need it to add or remove Cygwin packages in the future. I suggest moving the installer to the same folder where you installed Cygwin itself; typically C:\cygwin or C:\cygwin64. If you already have Cygwin

[Next page](<https://devfeed.tech/sources/jeff-preshing.md?cursor=WyIyMDE0LTExLTA4VDE1OjUwOjAwKzAwOjAwIiwgImI1YjMyZDM2LTIzMzYtNGQ3Yy1iN2U0LWI0YzA4OWRiNDZhNCJd>)