Is there something like a VM to wrap tools such as LLVM IRBuilder?
I'm working on a lightweight embedded scripting language for C++ applications. This is intended for modest extensions to the applications themselves, such as adding context-menu options to GUI controls (scripts are handlers for when the option is activated); parsers for loading data in custom serialization formats (scripts might be pairs of regex rules with match callbacks); or statistical analyses for data sets. The language has a VM which aims to be almost trivial, or at least have a minimal working core -- mostly instructions to build up a parameter list and call C++ code via function pointers. One of my goals is to minimize the distinction between calling C++ functions from a host application versus methods that implement basic language elements, like declaring/initializing variables, managing lexical scopes and variable lifetimes, and branching/loop blocks. For instance, instead of "jump" instructions if/else could be implemented as a C++ function whose second argument is an object encapsulating a code block.
My question is as follows: with this setup I am researching the feasibility of transpiling to C++ files rather than executing scripts immediately. For the basic language I seek to minimize heavy dependencies like LLVM (leaning more toward a much smaller infrastructure, like LuaVM). But I would accept external dependencies for optional extensions.
Generating C++ code directly via something like std::stringstream seems pretty awkward. I've read about Jank's IR from which C++ code is produced (and then, I believe, compiled immediately via Clang). Perhaps Gabriel dos Reis's IPR could be used to similar effect. Instead of compiling \*to\* IR, generate IR and decompile to C++ source code.
But since my compiler pipeline is designed to emit VM code, I'm hoping some tools might exist for which IR is more akin to instructions in some special-purpose bytecode format. Functionally, I'm envisioning something like LLVM IRBuilder, where code-generation is decomposed into lots of small actions (add some token to an argument list, open/close some code block, etc.). Even just a wrapper around IRBuilder might work. But what I hope to find is a sort of DSL where various IRBuilder methods (or the equivalent) could be written in sequence, one-line-per-instruction style. One thing confusing me is that online discussions about .ll files "decompiling" to C++ aren't clear as to whether the goal is generating IRBuilder code that would produce the equivalent .ll code, or conversely reconstructing the actual C++ originally written. Substantially though I'm not sure how much it matters. Here's what AI spits out as a simple IRBuilder example:
Type* Int32Ty = Type::getInt32Ty(Context);
std::vector<Type*> ParamTypes = {Int32Ty, Int32Ty};
FunctionType *FuncType = FunctionType::get(Int32Ty, ParamTypes, false);
Function *AddFunc = Function::Create(FuncType, Function::ExternalLinkage, "add", OwnerModule.get());
Function::arg_iterator Args = AddFunc->arg_begin();
Value* ArgA = Args++;
ArgA->setName("a");
Value* ArgB = Args;
ArgB->setName("b");
I could certainly envision an interface like this to produce equivalent C++ code:
int32_t add(int32_t a, int32_t b)
and so forth. But it would be excellent if the IRBuilder code could be replaced by something more VM-like:
init-arg-list
add-param-type @Int32Ty
add-param-type @Int32Ty
add-return-type @Int32Ty
reset-arg-cursor
set-arg-name "a"
inc-arg-cursor
set-arg-name "b"
inc-arg-cursor
set-proc-name "add"
write-function-signature
or something like that (imagining a "@" sigil on type names). The point is that the above lines might be pretty close to VM code intended to call the "add" function at runtime, so you could use the same compiler toolchain for multiple steps before generating one kind of code for runtime scripts and a different VM flavor for producing C++ source files.
I don't think there's any
I'm working on a lightweight embedded scripting language for C++ applications. This is intended for modest extensions to the applications themselves, such as adding context-menu options to GUI controls (scripts are handlers for when the option is activated); parsers for loading data in custom serialization formats (scripts might be pairs of regex rules with match callbacks); or statistical analyses for data sets. The language has a VM which aims to be almost trivial, or at least have a minimal working core -- mostly instructions to build up a parameter list and call C++ code via function pointers. One of my goals is to minimize the distinction between calling C++ functions from a host application versus methods that implement basic language elements, like declaring/initializing variables, managing lexical scopes and variable lifetimes, and branching/loop blocks. For instance, instead of "jump" instructions if/else could be implemented as a C++ function whose second argument is an object encapsulating a code block.
My question is as follows: with this setup I am researching the feasibility of transpiling to C++ files rather than executing scripts immediately. For the basic language I seek to minimize heavy dependencies like LLVM (leaning more toward a much smaller infrastructure, like LuaVM). But I would accept external dependencies for optional extensions.
Generating C++ code directly via something like std::stringstream seems pretty awkward. I've read about Jank's IR from which C++ code is produced (and then, I believe, compiled immediately via Clang). Perhaps Gabriel dos Reis's IPR could be used to similar effect. Instead of compiling \*to\* IR, generate IR and decompile to C++ source code.
But since my compiler pipeline is designed to emit VM code, I'm hoping some tools might exist for which IR is more akin to instructions in some special-purpose bytecode format. Functionally, I'm envisioning something like LLVM IRBuilder, where code-generation is decomposed into lots of small actions (add some token to an argument list, open/close some code block, etc.). Even just a wrapper around IRBuilder might work. But what I hope to find is a sort of DSL where various IRBuilder methods (or the equivalent) could be written in sequence, one-line-per-instruction style. One thing confusing me is that online discussions about .ll files "decompiling" to C++ aren't clear as to whether the goal is generating IRBuilder code that would produce the equivalent .ll code, or conversely reconstructing the actual C++ originally written. Substantially though I'm not sure how much it matters. Here's what AI spits out as a simple IRBuilder example:
Type* Int32Ty = Type::getInt32Ty(Context);
std::vector<Type*> ParamTypes = {Int32Ty, Int32Ty};
FunctionType *FuncType = FunctionType::get(Int32Ty, ParamTypes, false);
Function *AddFunc = Function::Create(FuncType, Function::ExternalLinkage, "add", OwnerModule.get());
Function::arg_iterator Args = AddFunc->arg_begin();
Value* ArgA = Args++;
ArgA->setName("a");
Value* ArgB = Args;
ArgB->setName("b");
I could certainly envision an interface like this to produce equivalent C++ code:
int32_t add(int32_t a, int32_t b)
and so forth. But it would be excellent if the IRBuilder code could be replaced by something more VM-like:
init-arg-list
add-param-type @Int32Ty
add-param-type @Int32Ty
add-return-type @Int32Ty
reset-arg-cursor
set-arg-name "a"
inc-arg-cursor
set-arg-name "b"
inc-arg-cursor
set-proc-name "add"
write-function-signature
or something like that (imagining a "@" sigil on type names). The point is that the above lines might be pretty close to VM code intended to call the "add" function at runtime, so you could use the same compiler toolchain for multiple steps before generating one kind of code for runtime scripts and a different VM flavor for producing C++ source files.
I don't think there's any
I built a 3D network router that "senses" attacks instead of just watching an alarm number
Built a 3D grid network simulator in C++. Packets move between nodes and reroute around traffic jams. On top of that, I built a controller that watches the overall behavior of the network — not just one alarm number — using 4 signals together: how full it is, how much is getting dropped, how fast it recovers after a spike, and how much room is left.
I compared it against a normal "alarm" style monitor — the kind most systems use, which only reacts once one number crosses a fixed line (here: more than 5% of traffic dropped, or the network more than 40% full)..
I threw 5 different fake attacks at both systems, across two network sizes, and added up the totals:
\\-Packets delivered:
my controller 1,091,830 vs normal monitor 613,472
(mine delivered 1.8x more)
\\-Average traffic lost, across ALL 5 attacks: mine (23% ) vs. normal monitor (28%)
(Quick note on those two percentages — some attacks are brutal and cause heavy loss no matter what, others are quiet and barely register. 23% and 28% are just the average across all of them combined. The real story is in the next part.)
Two of the five attacks — a slow quiet flood, and a sneaky targeted overload — never dropped more than 1% of traffic. That means the normal alarm-style monitor never noticed them at all, because it was only built to react once something gets loud, and these two stayed quiet on purpose.
My controller still caught both of them. Even though no single number spiked, the overall pattern still looked different from what normal traffic looks like — kind of like noticing something feels "off" about a room, even when nothing's visibly broken.
Code: https://github.com/Antriksh005/arena3d.
Been working on this for now some months , so Genuinely want criticism, especially on how I'm measuring "detection" — that part deserves scrutiny.
https://redd.it/1v7xg86
@r_cpp
Built a 3D grid network simulator in C++. Packets move between nodes and reroute around traffic jams. On top of that, I built a controller that watches the overall behavior of the network — not just one alarm number — using 4 signals together: how full it is, how much is getting dropped, how fast it recovers after a spike, and how much room is left.
I compared it against a normal "alarm" style monitor — the kind most systems use, which only reacts once one number crosses a fixed line (here: more than 5% of traffic dropped, or the network more than 40% full)..
I threw 5 different fake attacks at both systems, across two network sizes, and added up the totals:
\\-Packets delivered:
my controller 1,091,830 vs normal monitor 613,472
(mine delivered 1.8x more)
\\-Average traffic lost, across ALL 5 attacks: mine (23% ) vs. normal monitor (28%)
(Quick note on those two percentages — some attacks are brutal and cause heavy loss no matter what, others are quiet and barely register. 23% and 28% are just the average across all of them combined. The real story is in the next part.)
Two of the five attacks — a slow quiet flood, and a sneaky targeted overload — never dropped more than 1% of traffic. That means the normal alarm-style monitor never noticed them at all, because it was only built to react once something gets loud, and these two stayed quiet on purpose.
My controller still caught both of them. Even though no single number spiked, the overall pattern still looked different from what normal traffic looks like — kind of like noticing something feels "off" about a room, even when nothing's visibly broken.
Code: https://github.com/Antriksh005/arena3d.
Been working on this for now some months , so Genuinely want criticism, especially on how I'm measuring "detection" — that part deserves scrutiny.
https://redd.it/1v7xg86
@r_cpp
GitHub
GitHub - Antriksh005/arena3d
Contribute to Antriksh005/arena3d development by creating an account on GitHub.
AVX-512 Intrinsics Optimization: Achieving ~7% speedup over libpopcnt on Sapphire Rapids
Benchmarking random 64B cache-line jumps on Intel Xeon Sapphire Rapids showed the custom kernel achieving 7.09 ns/line, compared to
While contiguous memory performance ties
Target is v40. Looking for insights on whether software prefetching (
https://redd.it/1v86xcs
@r_cpp
Benchmarking random 64B cache-line jumps on Intel Xeon Sapphire Rapids showed the custom kernel achieving 7.09 ns/line, compared to
libpopcnt (7.58 ns) and std::popcount (46.10 ns).While contiguous memory performance ties
libpopcnt at 0.47 ns/word, the performance gain on this gather hot-path comes from maintaining accumulator states inside ZMM registers across steps and applying 2-accumulator unrolling to break dependency chains.Target is v40. Looking for insights on whether software prefetching (
_mm_prefetch) provides measurable benefits for this gather pattern or if latency is memory-bound.https://redd.it/1v86xcs
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
26)
```cpp
constexpr auto parse() {
// Allowed
static_assert(false, "Expected ';'");
// Not allowed :( (until C++ 26)
std::size_t line = 5;
static_assert(false, "Expected ';' at line " + to_string(line));
}
```
I didn't want my project to require C++ 26, so I used another trick. The formatted string gets turned into a static array just like a vector (into `const_string` actually) and then it's passed into `ErrorMessage<const_string Msg>` that triggers compilation error. So we force the compiler to print the full type name that includes our error. But sadly the type name has a limit about 100 symbols. I think I could solve it with splitting the message into several ErrorMessages... God, I don't want to read this in my console.
```c++
template<const_string Msg>
struct ErrorMessage {
static_assert(false, "Check the template parameter for details");
};
template<auto err_getter>
consteval auto report_error() -> void {
// C++ 26 support
#ifdef KORKA_FEATURE_FORMATTED_STATIC_ASSERT
static_assert(false, to_string(err_getter()));
#else
constexpr auto msg = const_string_from_string_view<[] { return to_string(err_getter()); }>();
std::ignore = ErrorMessage<msg>{};
#endif
}
```
I don't want you to see it, so I'll just show C++ 26 version.
```
error: static assertion failed: Lexer Error: Unterminated string at line 12
```
### Mapping signatures to names. And vice versa
In our little runtime C++ we are used to `std::unordered_map<string, value_t>` and other standard or non-standard (hello, Boost!) containers. But I needed a table where a key is a string and the value is a TYPE. And in C++ I can't treat types as values, I can't just put them into a dict... :(
So, welcome another hack!
```c++
template<auto, class>
struct signature_mapper;
// function_info_getter takes an index to our mapped function,
// and Is... holds all indices
template<auto function_info_getter, std::size_t... Is>
struct signature_mapper<
function_info_getter,
std::index_sequence<Is...>
> {
// hash func
consteval static auto hash(auto &&v) -> std::size_t {
return frozen::elsa<std::string_view>{}(v, 0);
}
// Our function overloaded with many unique types based on hash of the mapped function
constexpr static auto _overloaded = overloaded{
(
[](unique_type<hash(function_info_getter(Is).name)>)
-> const_function_info_to_signature_t<[] { return function_info_getter(Is); }> * {
return nullptr;
}
)...
};
// Extracting the type by name
template<const_string name>
using get_signature_t = std::remove_pointer_t<decltype(
_overloaded(
unique_type<hash(name)>{}
)
)>;
};
```
We use well-known function overload (~~but for evil things~~). Basically, one type inherits a lot of lambdas that take an empty `unique_type<hash>` that serves as our key and returns the pointer to our type.
```cpp
// How our mapper looks after expanding our params
struct overloaded : lambda1, lambda2, lambda3 {
using lambda1::operator();
using lambda2::operator();
using lambda3::operator();
};
// And every lambda looks like this
auto lambda_fib = [](unique_type<hash("fib")>) -> signature_of_fib* { return nullptr; };
```
When we call `_overloaded(unique_type<hash(name)>())` our poor compiler has to resolve the overload. And he looks for right one through all `()` operators. And then we just take that it returns (our `T*`) and get the `T`.
I use this "mechanism" to extract script functions into the native C++.
```cpp
constexpr auto script_fib = compile_result.function<"fib">();
```
### Bindings from C++ to our script lang
This was the most exhausting part. Well, how "exhausting" exactly... I was thinking for a few evenings and then made it work one morning. The problem was with me. I wanted to make a pretty API that was impossible in the current standard (maybe it's possible in C++ 26, but I didn't check it).
I wanted it to look like this:
```cpp
auto func() -> void;
auto foo(int) -> int;
// Примерно так
constexpr auto bindings = korka::make_bindings<
"func", func,
"foo", foo
>();
// Или так
constexpr auto
```cpp
constexpr auto parse() {
// Allowed
static_assert(false, "Expected ';'");
// Not allowed :( (until C++ 26)
std::size_t line = 5;
static_assert(false, "Expected ';' at line " + to_string(line));
}
```
I didn't want my project to require C++ 26, so I used another trick. The formatted string gets turned into a static array just like a vector (into `const_string` actually) and then it's passed into `ErrorMessage<const_string Msg>` that triggers compilation error. So we force the compiler to print the full type name that includes our error. But sadly the type name has a limit about 100 symbols. I think I could solve it with splitting the message into several ErrorMessages... God, I don't want to read this in my console.
```c++
template<const_string Msg>
struct ErrorMessage {
static_assert(false, "Check the template parameter for details");
};
template<auto err_getter>
consteval auto report_error() -> void {
// C++ 26 support
#ifdef KORKA_FEATURE_FORMATTED_STATIC_ASSERT
static_assert(false, to_string(err_getter()));
#else
constexpr auto msg = const_string_from_string_view<[] { return to_string(err_getter()); }>();
std::ignore = ErrorMessage<msg>{};
#endif
}
```
I don't want you to see it, so I'll just show C++ 26 version.
```
error: static assertion failed: Lexer Error: Unterminated string at line 12
```
### Mapping signatures to names. And vice versa
In our little runtime C++ we are used to `std::unordered_map<string, value_t>` and other standard or non-standard (hello, Boost!) containers. But I needed a table where a key is a string and the value is a TYPE. And in C++ I can't treat types as values, I can't just put them into a dict... :(
So, welcome another hack!
```c++
template<auto, class>
struct signature_mapper;
// function_info_getter takes an index to our mapped function,
// and Is... holds all indices
template<auto function_info_getter, std::size_t... Is>
struct signature_mapper<
function_info_getter,
std::index_sequence<Is...>
> {
// hash func
consteval static auto hash(auto &&v) -> std::size_t {
return frozen::elsa<std::string_view>{}(v, 0);
}
// Our function overloaded with many unique types based on hash of the mapped function
constexpr static auto _overloaded = overloaded{
(
[](unique_type<hash(function_info_getter(Is).name)>)
-> const_function_info_to_signature_t<[] { return function_info_getter(Is); }> * {
return nullptr;
}
)...
};
// Extracting the type by name
template<const_string name>
using get_signature_t = std::remove_pointer_t<decltype(
_overloaded(
unique_type<hash(name)>{}
)
)>;
};
```
We use well-known function overload (~~but for evil things~~). Basically, one type inherits a lot of lambdas that take an empty `unique_type<hash>` that serves as our key and returns the pointer to our type.
```cpp
// How our mapper looks after expanding our params
struct overloaded : lambda1, lambda2, lambda3 {
using lambda1::operator();
using lambda2::operator();
using lambda3::operator();
};
// And every lambda looks like this
auto lambda_fib = [](unique_type<hash("fib")>) -> signature_of_fib* { return nullptr; };
```
When we call `_overloaded(unique_type<hash(name)>())` our poor compiler has to resolve the overload. And he looks for right one through all `()` operators. And then we just take that it returns (our `T*`) and get the `T`.
I use this "mechanism" to extract script functions into the native C++.
```cpp
constexpr auto script_fib = compile_result.function<"fib">();
```
### Bindings from C++ to our script lang
This was the most exhausting part. Well, how "exhausting" exactly... I was thinking for a few evenings and then made it work one morning. The problem was with me. I wanted to make a pretty API that was impossible in the current standard (maybe it's possible in C++ 26, but I didn't check it).
I wanted it to look like this:
```cpp
auto func() -> void;
auto foo(int) -> int;
// Примерно так
constexpr auto bindings = korka::make_bindings<
"func", func,
"foo", foo
>();
// Или так
constexpr auto
C++ Show and Tell - August 2026
Use this thread to share anything you've written in C++. This includes:
* a tool you've written
* a game you've been working on
* your first non-trivial C++ program
The rules of this thread are very straight forward:
* The project must involve C++ in some way.
* It must be something you (alone or with others) have done.
* Please share a link, if applicable.
* Please post images, if applicable.
If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.
Last month's thread: https://www.reddit.com/r/cpp/comments/1umnaxs/c_show_and_tell_july_2026/
https://redd.it/1vhdqw8
@r_cpp
Use this thread to share anything you've written in C++. This includes:
* a tool you've written
* a game you've been working on
* your first non-trivial C++ program
The rules of this thread are very straight forward:
* The project must involve C++ in some way.
* It must be something you (alone or with others) have done.
* Please share a link, if applicable.
* Please post images, if applicable.
If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.
Last month's thread: https://www.reddit.com/r/cpp/comments/1umnaxs/c_show_and_tell_july_2026/
https://redd.it/1vhdqw8
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
C++ Show and Tell - September 2026
Use this thread to share anything you've written in C++. This includes:
* a tool you've written
* a game you've been working on
* your first non-trivial C++ program
The rules of this thread are very straight forward:
* The project must involve C++ in some way.
* It must be something you (alone or with others) have done.
* Please share a link, if applicable.
* Please post images, if applicable.
If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.
Last month's thread: https://www.reddit.com/r/cpp/comments/1vhdqw8/c_show_and_tell_august_2026/
https://redd.it/1w776o7
@r_cpp
Use this thread to share anything you've written in C++. This includes:
* a tool you've written
* a game you've been working on
* your first non-trivial C++ program
The rules of this thread are very straight forward:
* The project must involve C++ in some way.
* It must be something you (alone or with others) have done.
* Please share a link, if applicable.
* Please post images, if applicable.
If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.
Last month's thread: https://www.reddit.com/r/cpp/comments/1vhdqw8/c_show_and_tell_august_2026/
https://redd.it/1w776o7
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
C++ Show and Tell - October 2026
Use this thread to share anything you've written in C++. This includes:
* a tool you've written
* a game you've been working on
* your first non-trivial C++ program
The rules of this thread are very straight forward:
* The project must involve C++ in some way.
* It must be something you (alone or with others) have done.
* Please share a link, if applicable.
* Please post images, if applicable.
If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.
Last month's thread: https://www.reddit.com/r/cpp/comments/1w776o7/c_show_and_tell_september_2026/
https://redd.it/1wwiz8g
@r_cpp
Use this thread to share anything you've written in C++. This includes:
* a tool you've written
* a game you've been working on
* your first non-trivial C++ program
The rules of this thread are very straight forward:
* The project must involve C++ in some way.
* It must be something you (alone or with others) have done.
* Please share a link, if applicable.
* Please post images, if applicable.
If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.
Last month's thread: https://www.reddit.com/r/cpp/comments/1w776o7/c_show_and_tell_september_2026/
https://redd.it/1wwiz8g
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
No, -Wall -Werror Does Not Guarantee Detection of Conditionally Uninitialized Local Variables
There seems to be a misconception or lack of clarity about the usage of the compilation flags -Wall and -Werror and their ability to detect uninitialized stack variables. It depends. In this post, I will try to explore this further and explain when and how it is detected, and where it may not detect an uninitialized local variable and hence requires more caution while dealing with it. Consider the following code:
int main()
{
int value;
return value;
}
Compile this code as follows:
~/cpp_26_uninitialised$ g++ -std=c++23 -Wall -Werror test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:4:12: error: ‘value’ is used uninitialized [-Werror=uninitialized]
4 | return value;
| ^~~~~
test.cpp:3:9: note: ‘value’ was declared here
3 | int value;
| ^~~~~
cc1plus: all warnings being treated as errors
So, with the use of the two compilation flags, `-Wall` and `-Werror`, the compilation fails, and you can then take corrective measures to address the uninitialized variable in the code.
Strictly speaking, -Wall enables the -Wuninitialized warning, and -Werror turns that warning into an error. However, *this is true only when the variable is uninitialized on every path to its use*, as `value` is here. It doesn't reliably work for a variable that is initialized on some paths and left uninitialized on others. Have a look at the following code:
// config_timeout_warning_test.cpp
#include <charconv>
#include <cstdio>
#include <string_view>
constexpr int default_timeout_ms = 1000;
// Reads "timeout_ms=<number>" from a device configuration line.
// The bug: when the key is missing, timeout_ms is never assigned.
[[gnu::noinline]] int read_timeout_ms(std::string_view config)
{
int timeout_ms;
constexpr std::string_view key = "timeout_ms=";
if (const auto pos = config.find(key); pos != std::string_view::npos)
{
const char* first = config.data() + pos + key.size();
const char* last = config.data() + config.size();
std::from_chars(first, last, timeout_ms);
}
return timeout_ms;
}
void open_device(const char* name, std::string_view config)
{
const int timeout_ms = read_timeout_ms(config);
if (timeout_ms <= 0)
{
std::printf("%-7s no timeout configured, using default %d ms\n", name, default_timeout_ms);
}
else
{
std::printf("%-7s timeout %d ms\n", name, timeout_ms);
}
}
int main()
{
// The empty configuration does not contain "timeout_ms=".
// Therefore, timeout_ms is returned without being initialized.
open_device("logger", "");
return 0;
}
Compile the code as follows:
~/cpp_26_uninitialised$ g++ -std=c++23 -O0 -g -Wall -Werror config_timeout_warning_test.cpp -o timeout_warning_test
The compilation succeeds without a single warning. Run Valgrind on it:
~/cpp_26_uninitialised$ valgrind --track-origins=yes ./timeout_warning_test
==2896379== Memcheck, a memory error detector
==2896379== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2896379== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==2896379== Command: ./timeout_warning_test
==2896379==
==2896379== Conditional jump or move depends on uninitialised value(s)
==2896379== at 0x401268: open_device(char const*, std::basic_string_view<char, std::char_traits<char> >) (config_timeout_warning_test.cpp:31)
==2896379== by 0x4012D3: main (config_timeout_warning_test.cpp:45)
==2896379== Uninitialised value was created by a stack allocation
==2896379== at 0x401166: read_timeout_ms(std::basic_string_view<char, std::char_traits<char> >) (config_timeout_warning_test.cpp:10)
There seems to be a misconception or lack of clarity about the usage of the compilation flags -Wall and -Werror and their ability to detect uninitialized stack variables. It depends. In this post, I will try to explore this further and explain when and how it is detected, and where it may not detect an uninitialized local variable and hence requires more caution while dealing with it. Consider the following code:
int main()
{
int value;
return value;
}
Compile this code as follows:
~/cpp_26_uninitialised$ g++ -std=c++23 -Wall -Werror test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:4:12: error: ‘value’ is used uninitialized [-Werror=uninitialized]
4 | return value;
| ^~~~~
test.cpp:3:9: note: ‘value’ was declared here
3 | int value;
| ^~~~~
cc1plus: all warnings being treated as errors
So, with the use of the two compilation flags, `-Wall` and `-Werror`, the compilation fails, and you can then take corrective measures to address the uninitialized variable in the code.
Strictly speaking, -Wall enables the -Wuninitialized warning, and -Werror turns that warning into an error. However, *this is true only when the variable is uninitialized on every path to its use*, as `value` is here. It doesn't reliably work for a variable that is initialized on some paths and left uninitialized on others. Have a look at the following code:
// config_timeout_warning_test.cpp
#include <charconv>
#include <cstdio>
#include <string_view>
constexpr int default_timeout_ms = 1000;
// Reads "timeout_ms=<number>" from a device configuration line.
// The bug: when the key is missing, timeout_ms is never assigned.
[[gnu::noinline]] int read_timeout_ms(std::string_view config)
{
int timeout_ms;
constexpr std::string_view key = "timeout_ms=";
if (const auto pos = config.find(key); pos != std::string_view::npos)
{
const char* first = config.data() + pos + key.size();
const char* last = config.data() + config.size();
std::from_chars(first, last, timeout_ms);
}
return timeout_ms;
}
void open_device(const char* name, std::string_view config)
{
const int timeout_ms = read_timeout_ms(config);
if (timeout_ms <= 0)
{
std::printf("%-7s no timeout configured, using default %d ms\n", name, default_timeout_ms);
}
else
{
std::printf("%-7s timeout %d ms\n", name, timeout_ms);
}
}
int main()
{
// The empty configuration does not contain "timeout_ms=".
// Therefore, timeout_ms is returned without being initialized.
open_device("logger", "");
return 0;
}
Compile the code as follows:
~/cpp_26_uninitialised$ g++ -std=c++23 -O0 -g -Wall -Werror config_timeout_warning_test.cpp -o timeout_warning_test
The compilation succeeds without a single warning. Run Valgrind on it:
~/cpp_26_uninitialised$ valgrind --track-origins=yes ./timeout_warning_test
==2896379== Memcheck, a memory error detector
==2896379== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2896379== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==2896379== Command: ./timeout_warning_test
==2896379==
==2896379== Conditional jump or move depends on uninitialised value(s)
==2896379== at 0x401268: open_device(char const*, std::basic_string_view<char, std::char_traits<char> >) (config_timeout_warning_test.cpp:31)
==2896379== by 0x4012D3: main (config_timeout_warning_test.cpp:45)
==2896379== Uninitialised value was created by a stack allocation
==2896379== at 0x401166: read_timeout_ms(std::basic_string_view<char, std::char_traits<char> >) (config_timeout_warning_test.cpp:10)
BqLog 2.6.0: a C++ logging library running on 30M+ devices daily, benchmarked against quill, fmtlog, spdlog and glog (time, CPU and memory)
BqLog is a cross-platform logging library open-sourced by Tencent two years ago. Since then it has gone through two more years of production use and improved a lot in performance, reliability, compatibility and developer experience. With 2.6.0 out, I'd like to introduce it here again.
BqLog is used in a number of Tencent's commercial products, including performance-sensitive mobile games such as Honor of Kings, as well as their server-side logic. It runs on more than 30 million devices every day, across a very wide range of hardware, networks and storage, so its stability and performance have held up in mature commercial products over a long time.
Design goals
Extreme speed is where BqLog starts, not where it stops. It is a mature, industrial-grade component, built for products that ship:
- Content to play a supporting role. On a modern machine a logging system should take as little of the system as it can. The logging threads and the consumer thread alike should use as little CPU, memory and disk I/O as possible. We do not optimize for benchmark scores; every optimization targets real use.
- Compression and encryption without giving up speed. The real-time compressed format is about 1/7 the size of text, and writing it is faster and uses less CPU than writing text. Hybrid RSA+AES encryption is supported and costs almost nothing in performance.
- Compatible everywhere it runs. Windows, macOS, Linux, iOS, Android, HarmonyOS, OpenHarmony and the Unix family; C++, Java/Kotlin, C#, Python, TypeScript/ArkTS and Go sharing one core and even one log object; game engines, mobile toolchains without an STL, strict
- Built for the bad day. Logs written before a crash are recovered after it; a full disk neither crashes nor hangs the app; corrupted files are recovered as far as possible; log files can be encrypted to protect privacy.
- Care about the coding experience. One line to create a log, one line to write; the internals stay as transparent as possible, without complicated configuration; every interface is friendly to IDE code completion; integration tools such as UE Blueprints are provided.
Performance
2.6.0 comes with a new, complete benchmark against quill, fmtlog, spdlog, glog and Log4j2, and every result reports time, CPU and memory together. In short:
- Throughput: on macOS and Windows, BqLog has the shortest total time at every thread count. The compressed format is roughly 4 to 12 times faster than the fastest of the other libraries and also has the lowest CPU time; the text format is 1.5 to 4.6 times faster.
- Cost per call on the logging thread: BqLog, quill and fmtlog are in the same tier, with BqLog averaging under 20 ns per call on all three platforms; spdlog is more than an order of magnitude slower.
- Memory: with fixed-size buffers, BqLog's peak memory is in the lowest tier and barely grows with more threads; with growing buffers it is about half of quill's or less.
- File size: the compressed format is about 1/7 the size of text.
On Linux only latency is listed for now. On the VMs we tried, throughput was dominated by the VM's disk scheduling and varied by up to 2x between rounds, so we left it out. The test scripts are in the repo, and if you have a bare-metal Linux box we'd be glad to see your numbers.
Methodology, library configurations and full data: https://github.com/Tencent/BqLog/blob/main/docs/BENCHMARK.md
Technical write-ups
If you're curious why BqLog is fast, there are three articles:
1. High-Performance Realtime Compressed Log Format: https://github.com/Tencent/BqLog/blob/main/docs/Article%201Why%20is%20BqLog%20so%20fast%20-%20High%20Performance%20Realtime%20Compressed%20Log%20Format.MD
2. From Ring Buffer to Adaptive Data Bus: https://github.com/Tencent/BqLog/blob/main/docs/Article%202Why%20is%20BqLog%20so%20fast%20-%20From%20Ring%20Buffer%20to%20Adaptive%20Data%20Bus.MD
3.
BqLog is a cross-platform logging library open-sourced by Tencent two years ago. Since then it has gone through two more years of production use and improved a lot in performance, reliability, compatibility and developer experience. With 2.6.0 out, I'd like to introduce it here again.
BqLog is used in a number of Tencent's commercial products, including performance-sensitive mobile games such as Honor of Kings, as well as their server-side logic. It runs on more than 30 million devices every day, across a very wide range of hardware, networks and storage, so its stability and performance have held up in mature commercial products over a long time.
Design goals
Extreme speed is where BqLog starts, not where it stops. It is a mature, industrial-grade component, built for products that ship:
- Content to play a supporting role. On a modern machine a logging system should take as little of the system as it can. The logging threads and the consumer thread alike should use as little CPU, memory and disk I/O as possible. We do not optimize for benchmark scores; every optimization targets real use.
- Compression and encryption without giving up speed. The real-time compressed format is about 1/7 the size of text, and writing it is faster and uses less CPU than writing text. Hybrid RSA+AES encryption is supported and costs almost nothing in performance.
- Compatible everywhere it runs. Windows, macOS, Linux, iOS, Android, HarmonyOS, OpenHarmony and the Unix family; C++, Java/Kotlin, C#, Python, TypeScript/ArkTS and Go sharing one core and even one log object; game engines, mobile toolchains without an STL, strict
-Werror builds.- Built for the bad day. Logs written before a crash are recovered after it; a full disk neither crashes nor hangs the app; corrupted files are recovered as far as possible; log files can be encrypted to protect privacy.
- Care about the coding experience. One line to create a log, one line to write; the internals stay as transparent as possible, without complicated configuration; every interface is friendly to IDE code completion; integration tools such as UE Blueprints are provided.
Performance
2.6.0 comes with a new, complete benchmark against quill, fmtlog, spdlog, glog and Log4j2, and every result reports time, CPU and memory together. In short:
- Throughput: on macOS and Windows, BqLog has the shortest total time at every thread count. The compressed format is roughly 4 to 12 times faster than the fastest of the other libraries and also has the lowest CPU time; the text format is 1.5 to 4.6 times faster.
- Cost per call on the logging thread: BqLog, quill and fmtlog are in the same tier, with BqLog averaging under 20 ns per call on all three platforms; spdlog is more than an order of magnitude slower.
- Memory: with fixed-size buffers, BqLog's peak memory is in the lowest tier and barely grows with more threads; with growing buffers it is about half of quill's or less.
- File size: the compressed format is about 1/7 the size of text.
On Linux only latency is listed for now. On the VMs we tried, throughput was dominated by the VM's disk scheduling and varied by up to 2x between rounds, so we left it out. The test scripts are in the repo, and if you have a bare-metal Linux box we'd be glad to see your numbers.
Methodology, library configurations and full data: https://github.com/Tencent/BqLog/blob/main/docs/BENCHMARK.md
Technical write-ups
If you're curious why BqLog is fast, there are three articles:
1. High-Performance Realtime Compressed Log Format: https://github.com/Tencent/BqLog/blob/main/docs/Article%201Why%20is%20BqLog%20so%20fast%20-%20High%20Performance%20Realtime%20Compressed%20Log%20Format.MD
2. From Ring Buffer to Adaptive Data Bus: https://github.com/Tencent/BqLog/blob/main/docs/Article%202Why%20is%20BqLog%20so%20fast%20-%20From%20Ring%20Buffer%20to%20Adaptive%20Data%20Bus.MD
3.
GitHub
BqLog/docs/BENCHMARK.md at main · Tencent/BqLog
Maybe the world's fastest logging library. Lightweight & industrial-grade, battle-tested in Honor of Kings. C++/Python/Java/C#/Kotlin/TS/Go, Unity/Unreal/HarmonyOS. 可能是全球最快的日志库——轻量级...
BqLog 2.6.0: a C++ logging library running on 30M+ devices daily, benchmarked against quill, fmtlog, spdlog and glog (time, CPU and memory)
BqLog is a cross-platform logging library open-sourced by Tencent two years ago. Since then it has gone through two more years of production use and improved a lot in performance, reliability, compatibility and developer experience. With 2.6.0 out, I'd like to introduce it here again.
BqLog is used in a number of Tencent's commercial products, including performance-sensitive mobile games such as Honor of Kings, as well as their server-side logic. It runs on more than 30 million devices every day, across a very wide range of hardware, networks and storage, so its stability and performance have held up in mature commercial products over a long time.
**Design goals**
**Extreme speed is where BqLog starts, not where it stops.** It is a mature, industrial-grade component, built for products that ship:
- **Content to play a supporting role.** On a modern machine a logging system should take as little of the system as it can. The logging threads and the consumer thread alike should use as little CPU, memory and disk I/O as possible. We do not optimize for benchmark scores; every optimization targets real use.
- **Compression and encryption without giving up speed.** The real-time compressed format is about 1/7 the size of text, and writing it is faster and uses less CPU than writing text. Hybrid RSA+AES encryption is supported and costs almost nothing in performance.
- **Compatible everywhere it runs.** Windows, macOS, Linux, iOS, Android, HarmonyOS, OpenHarmony and the Unix family; C++, Java/Kotlin, C#, Python, TypeScript/ArkTS and Go sharing one core and even one log object; game engines, mobile toolchains without an STL, strict `-Werror` builds.
- **Built for the bad day.** Logs written before a crash are recovered after it; a full disk neither crashes nor hangs the app; corrupted files are recovered as far as possible; log files can be encrypted to protect privacy.
- **Care about the coding experience.** One line to create a log, one line to write; the internals stay as transparent as possible, without complicated configuration; every interface is friendly to IDE code completion; integration tools such as UE Blueprints are provided.
**Performance**
2.6.0 comes with a new, complete benchmark against quill, fmtlog, spdlog, glog and Log4j2, and every result reports time, CPU and memory together. In short:
- **Throughput:** on macOS and Windows, BqLog has the shortest total time at every thread count. The compressed format is roughly 4 to 12 times faster than the fastest of the other libraries and also has the lowest CPU time; the text format is 1.5 to 4.6 times faster.
- **Cost per call on the logging thread:** BqLog, quill and fmtlog are in the same tier, with BqLog averaging under 20 ns per call on all three platforms; spdlog is more than an order of magnitude slower.
- **Memory:** with fixed-size buffers, BqLog's peak memory is in the lowest tier and barely grows with more threads; with growing buffers it is about half of quill's or less.
- **File size:** the compressed format is about 1/7 the size of text.
On Linux only latency is listed for now. On the VMs we tried, throughput was dominated by the VM's disk scheduling and varied by up to 2x between rounds, so we left it out. The test scripts are in the repo, and if you have a bare-metal Linux box we'd be glad to see your numbers.
Methodology, library configurations and full data: https://github.com/Tencent/BqLog/blob/main/docs/BENCHMARK.md
**Technical write-ups**
If you're curious why BqLog is fast, there are three articles:
1. High-Performance Realtime Compressed Log Format: https://github.com/Tencent/BqLog/blob/main/docs/Article%201_Why%20is%20BqLog%20so%20fast%20-%20High%20Performance%20Realtime%20Compressed%20Log%20Format.MD
2. From Ring Buffer to Adaptive Data Bus: https://github.com/Tencent/BqLog/blob/main/docs/Article%202_Why%20is%20BqLog%20so%20fast%20-%20From%20Ring%20Buffer%20to%20Adaptive%20Data%20Bus.MD
3.
BqLog is a cross-platform logging library open-sourced by Tencent two years ago. Since then it has gone through two more years of production use and improved a lot in performance, reliability, compatibility and developer experience. With 2.6.0 out, I'd like to introduce it here again.
BqLog is used in a number of Tencent's commercial products, including performance-sensitive mobile games such as Honor of Kings, as well as their server-side logic. It runs on more than 30 million devices every day, across a very wide range of hardware, networks and storage, so its stability and performance have held up in mature commercial products over a long time.
**Design goals**
**Extreme speed is where BqLog starts, not where it stops.** It is a mature, industrial-grade component, built for products that ship:
- **Content to play a supporting role.** On a modern machine a logging system should take as little of the system as it can. The logging threads and the consumer thread alike should use as little CPU, memory and disk I/O as possible. We do not optimize for benchmark scores; every optimization targets real use.
- **Compression and encryption without giving up speed.** The real-time compressed format is about 1/7 the size of text, and writing it is faster and uses less CPU than writing text. Hybrid RSA+AES encryption is supported and costs almost nothing in performance.
- **Compatible everywhere it runs.** Windows, macOS, Linux, iOS, Android, HarmonyOS, OpenHarmony and the Unix family; C++, Java/Kotlin, C#, Python, TypeScript/ArkTS and Go sharing one core and even one log object; game engines, mobile toolchains without an STL, strict `-Werror` builds.
- **Built for the bad day.** Logs written before a crash are recovered after it; a full disk neither crashes nor hangs the app; corrupted files are recovered as far as possible; log files can be encrypted to protect privacy.
- **Care about the coding experience.** One line to create a log, one line to write; the internals stay as transparent as possible, without complicated configuration; every interface is friendly to IDE code completion; integration tools such as UE Blueprints are provided.
**Performance**
2.6.0 comes with a new, complete benchmark against quill, fmtlog, spdlog, glog and Log4j2, and every result reports time, CPU and memory together. In short:
- **Throughput:** on macOS and Windows, BqLog has the shortest total time at every thread count. The compressed format is roughly 4 to 12 times faster than the fastest of the other libraries and also has the lowest CPU time; the text format is 1.5 to 4.6 times faster.
- **Cost per call on the logging thread:** BqLog, quill and fmtlog are in the same tier, with BqLog averaging under 20 ns per call on all three platforms; spdlog is more than an order of magnitude slower.
- **Memory:** with fixed-size buffers, BqLog's peak memory is in the lowest tier and barely grows with more threads; with growing buffers it is about half of quill's or less.
- **File size:** the compressed format is about 1/7 the size of text.
On Linux only latency is listed for now. On the VMs we tried, throughput was dominated by the VM's disk scheduling and varied by up to 2x between rounds, so we left it out. The test scripts are in the repo, and if you have a bare-metal Linux box we'd be glad to see your numbers.
Methodology, library configurations and full data: https://github.com/Tencent/BqLog/blob/main/docs/BENCHMARK.md
**Technical write-ups**
If you're curious why BqLog is fast, there are three articles:
1. High-Performance Realtime Compressed Log Format: https://github.com/Tencent/BqLog/blob/main/docs/Article%201_Why%20is%20BqLog%20so%20fast%20-%20High%20Performance%20Realtime%20Compressed%20Log%20Format.MD
2. From Ring Buffer to Adaptive Data Bus: https://github.com/Tencent/BqLog/blob/main/docs/Article%202_Why%20is%20BqLog%20so%20fast%20-%20From%20Ring%20Buffer%20to%20Adaptive%20Data%20Bus.MD
3.
GitHub
BqLog/docs/BENCHMARK.md at main · Tencent/BqLog
Maybe the world's fastest logging library. Lightweight & industrial-grade, battle-tested in Honor of Kings. C++/Python/Java/C#/Kotlin/TS/Go, Unity/Unreal/HarmonyOS. 可能是全球最快的日志库——轻量级...
The intention and spirit behind modules seem diametrically opposed to their actual implementations by compiler toolchains.
The lynchpin of C++ modules is the built module interface (BMI). Each BMI is meant to be a lightweight data structure representing the syntax of a module unit (comprised of one primary module interface and potentially one or more partitions), with approximately O(1) complexity of symbol lookup. This massively accelerates repeated lookups into the same translation unit, and avoids paying the cost of a full preprocessor run and front-end lex + parse, as might otherwise happen with header files. In this way both the first clean build, and incremental builds are considerably accelerated and made much more efficient—build the BMI once, reuse it across future compiles, and we don't need large core counts and massively parallel jobs because the BMI is now available afterwards.
However, the way compiler toolchains have actually implemented them seems diametrically opposed to this goal of fast lookup. Today, BMIs are highly sensitive to any change in the command-line invocation of the compiler/dependency scanning tool, including the C++ version, warning and feature flags, and especially macro definitions, with
BMIs are considered implementation details, and aren't even stable across compiler versions within the same toolchain. Compare to object files, where something compiled by really old versions can still be used on newer versions without too much fuss. This, from the user's perspective, entirely defeats that design ideal mentioned above: fast repeated lookups. Consider a simple example: a certain module uses a project-specific macro representing the platform, to change several function signatures. This module is now precompiled thrice, once each for
I believe that macros and the preprocessor are highly problematic. However, their very limitations are also an advantage here: their effect on code collapses to completely binary decisions. A macro is either defined or not, and a macro is either in the set of accepted values, or it isn't (e.g.
This would make things like library feature configuration with macros really straightforward—specify the macros one wants for that feature at the command-line, which is enshrined in build system code rather than source code—the BMI can be reused, done.
Now, the compiler and C++ standard are a lot harder as these probably affect the internal state of the compiler rather than merely the value of
As mentioned above, build systems are also forced into this rather inefficient model to accommodate compiler behaviour. CMake in its latest
The lynchpin of C++ modules is the built module interface (BMI). Each BMI is meant to be a lightweight data structure representing the syntax of a module unit (comprised of one primary module interface and potentially one or more partitions), with approximately O(1) complexity of symbol lookup. This massively accelerates repeated lookups into the same translation unit, and avoids paying the cost of a full preprocessor run and front-end lex + parse, as might otherwise happen with header files. In this way both the first clean build, and incremental builds are considerably accelerated and made much more efficient—build the BMI once, reuse it across future compiles, and we don't need large core counts and massively parallel jobs because the BMI is now available afterwards.
However, the way compiler toolchains have actually implemented them seems diametrically opposed to this goal of fast lookup. Today, BMIs are highly sensitive to any change in the command-line invocation of the compiler/dependency scanning tool, including the C++ version, warning and feature flags, and especially macro definitions, with
-DMACRO or /DMACRO. This means that changing just one flag is likely to cause a BMI cache miss and a full BMI reconstruction, which can be fairly slow for larger modules (like module std).BMIs are considered implementation details, and aren't even stable across compiler versions within the same toolchain. Compare to object files, where something compiled by really old versions can still be used on newer versions without too much fuss. This, from the user's perspective, entirely defeats that design ideal mentioned above: fast repeated lookups. Consider a simple example: a certain module uses a project-specific macro representing the platform, to change several function signatures. This module is now precompiled thrice, once each for
-DFOO_WINDOWS, -DFOO_DARWIN, -DFOO_LINUX, instead of just once.I believe that macros and the preprocessor are highly problematic. However, their very limitations are also an advantage here: their effect on code collapses to completely binary decisions. A macro is either defined or not, and a macro is either in the set of accepted values, or it isn't (e.g.
#if __cplusplus >= 202603L). The preprocessor state might change throughout the source code of a translation unit, but the entire set of possible states can be enumerated in finite and reasonably short time at compile time—otherwise the front-end would never complete its work. To me, this seems like the preprocessor and parser could enumerate all possible preprocessor states of the source code, and stamp out both possibilities for each macro switch in the BMI; during lookup, the compiler can select the correct code path depending on what is provided at that particular invocation (not code definitions, but command-line invocations, as this would break the module assurance that macros do not leak into BMIs from consumers, nor do consumers see macros from a BMI). This would make things like library feature configuration with macros really straightforward—specify the macros one wants for that feature at the command-line, which is enshrined in build system code rather than source code—the BMI can be reused, done.
Now, the compiler and C++ standard are a lot harder as these probably affect the internal state of the compiler rather than merely the value of
__cplusplus; however, I genuinely feel like there really ought to be a better way forward, especially if C++ is to continue as a 'source may not be available' language. This discussion is moot if we always want to compile from source, but I want to say that is wasteful, and another driving force of the modules feature was to do away with wasteful and repeated recomputation of the same thing.As mentioned above, build systems are also forced into this rather inefficient model to accommodate compiler behaviour. CMake in its latest
iteration, for instance, has a notion of 'BMI compatibility', and probably does some sort of set manipulation on compile flags to determine if another BMI for the same module interface is needed or not, based on how it is
I'm sure I don't have the entire picture as I am not a compiler front-end developer, and I don't mean to sound impertinent here, the effort put into delivering modules has been huge. However there are some decisions made which, as modules user and advocate, seem a little contradictory to the spirit of modules. I've written this after some thought on the situation and I'm interested in hearing from the community and compiler front-end developers who have worked on modules on my thoughts above.
Cheers.
https://redd.it/1x9famy
@r_cpp
imported. Why? This shouldn't be the case, a BMI really ought to be widely (if not universally) compatible, regardless of what flags go in the command-line. I'm sure I don't have the entire picture as I am not a compiler front-end developer, and I don't mean to sound impertinent here, the effort put into delivering modules has been huge. However there are some decisions made which, as modules user and advocate, seem a little contradictory to the spirit of modules. I've written this after some thought on the situation and I'm interested in hearing from the community and compiler front-end developers who have worked on modules on my thoughts above.
Cheers.
https://redd.it/1x9famy
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
Pain of making a native GUI in cpp
So I just wanted to vent about the absolute pain of making a working gui in cpp, I am working on a scientific project to make an openFOAM gui and browse openFOAM code to add TENO schemes to it from scientific papers such as Fu et al and working through the binaries.
I have not used AI in this project because CFD is very delicate and quite frankly, AI is not ready for such complexity - especially numerical schemes such as TENO, I ended up writing the meshing, topological code and mathematics myself and by far, the hardest part was the gui coordinates and memory management. I wanted to PULL MY HAIR OUT because of managing segfaults, crashes because of a random pointer hidden inside a 2000 line function, I had to also manage internal functions of openfoam(and you know how that goes), boundary conditions, and mesh topology, it was driving me nuts. I generally regard myself as fluent in programming languages such as cpp, python, rust etc, but this is a whole nother level data management.
in the end it turned out to be a pretty good contribution to the openFOAM community, hopefully the project will mature further and I will be able to write a paper on it.
https://redd.it/1xezb1k
@r_cpp
So I just wanted to vent about the absolute pain of making a working gui in cpp, I am working on a scientific project to make an openFOAM gui and browse openFOAM code to add TENO schemes to it from scientific papers such as Fu et al and working through the binaries.
I have not used AI in this project because CFD is very delicate and quite frankly, AI is not ready for such complexity - especially numerical schemes such as TENO, I ended up writing the meshing, topological code and mathematics myself and by far, the hardest part was the gui coordinates and memory management. I wanted to PULL MY HAIR OUT because of managing segfaults, crashes because of a random pointer hidden inside a 2000 line function, I had to also manage internal functions of openfoam(and you know how that goes), boundary conditions, and mesh topology, it was driving me nuts. I generally regard myself as fluent in programming languages such as cpp, python, rust etc, but this is a whole nother level data management.
in the end it turned out to be a pretty good contribution to the openFOAM community, hopefully the project will mature further and I will be able to write a paper on it.
https://redd.it/1xezb1k
@r_cpp
arXiv.org
A class of new high-order finite-volume TENO schemes for...
The recently proposed high-order TENO scheme [Fu et al., Journal of Computational Physics, 305, pp.333-359] has shown great potential in predicting complex fluids owing to the novel weighting...
My proposal for a cleaner text ticker / typewriter effect syntax in C++
I realized my previous error concept was flawed and that similar things already exist in C++, so I put some thought into it and came up with a cleaner, much easier wrapper.
To display text character-by-character (or in chunks of a few letters) in standard C++, you usually have to write a decent amount of boilerplate code. My goal was to eliminate all that extra writing. With this design, you only need to write a few concise lines, like in the image at the bottom.
Here is how it works:
1. **Block Configuration:** In the first line, `std::text_ticker(text_size(100))` sets up the configuration block. `text_size` defines a size limit applied to **each individual text object** inside the scope (in this case, up to 100 characters per string). If an individual text exceeds this limit, it triggers an error.
2. **Creating & Configuring Variables:** Inside the block, we create a `std::string` variable (e.g., `Home`). We assign it using `text(...)`, which defines the three core properties of the ticker:
* **Content:** The actual string in quotes (e.g., `"Home"`).
* **Step / Chunk Size:** How many characters to display at a time (e.g., `3`). For `"Home"` (4 letters), it will display the first 3 letters first, and then the remaining letter `e` next.
* **Delay (ms):** The delay between chunks in milliseconds (e.g., `400` ms, which is 0.4s).
You can also reassign a new text configuration to the same variable later on, like `Home = text("Hello", 1, 800);`, which instantly updates its content, chunk step, and timing properties.
Currently, I'm thinking about the best way to handle the actual execution/triggering of the print loop (maybe using memory addresses, unique IDs, or custom stream operators).
std::text_ticker(text_size(100))
{
std::string Home = text("Home", 3, 400);
Home = text("Hello", 1, 800 )
}
We can see things like range-based `for` loops here. For some people, that's already a piece of cake, but I think my way might be a bit different or easier for anyone who prefers this style. There will be more features added soon, like changing the text color for specific strings.
I'm not claiming this is the ultimate standard, because I know similar tools and range-based loops already exist, but I'm just trying something out to see if people find it useful or neat.
If you agree with me or like the idea, feel free to drop a positive comment or an upvote!
What do you think about this approach to keeping text animation syntax short and clean?
https://redd.it/1xexwwr
@r_cpp
I realized my previous error concept was flawed and that similar things already exist in C++, so I put some thought into it and came up with a cleaner, much easier wrapper.
To display text character-by-character (or in chunks of a few letters) in standard C++, you usually have to write a decent amount of boilerplate code. My goal was to eliminate all that extra writing. With this design, you only need to write a few concise lines, like in the image at the bottom.
Here is how it works:
1. **Block Configuration:** In the first line, `std::text_ticker(text_size(100))` sets up the configuration block. `text_size` defines a size limit applied to **each individual text object** inside the scope (in this case, up to 100 characters per string). If an individual text exceeds this limit, it triggers an error.
2. **Creating & Configuring Variables:** Inside the block, we create a `std::string` variable (e.g., `Home`). We assign it using `text(...)`, which defines the three core properties of the ticker:
* **Content:** The actual string in quotes (e.g., `"Home"`).
* **Step / Chunk Size:** How many characters to display at a time (e.g., `3`). For `"Home"` (4 letters), it will display the first 3 letters first, and then the remaining letter `e` next.
* **Delay (ms):** The delay between chunks in milliseconds (e.g., `400` ms, which is 0.4s).
You can also reassign a new text configuration to the same variable later on, like `Home = text("Hello", 1, 800);`, which instantly updates its content, chunk step, and timing properties.
Currently, I'm thinking about the best way to handle the actual execution/triggering of the print loop (maybe using memory addresses, unique IDs, or custom stream operators).
std::text_ticker(text_size(100))
{
std::string Home = text("Home", 3, 400);
Home = text("Hello", 1, 800 )
}
We can see things like range-based `for` loops here. For some people, that's already a piece of cake, but I think my way might be a bit different or easier for anyone who prefers this style. There will be more features added soon, like changing the text color for specific strings.
I'm not claiming this is the ultimate standard, because I know similar tools and range-based loops already exist, but I'm just trying something out to see if people find it useful or neat.
If you agree with me or like the idea, feel free to drop a positive comment or an upvote!
What do you think about this approach to keeping text animation syntax short and clean?
https://redd.it/1xexwwr
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
C++ Show and Tell - November 2026
Use this thread to share anything you've written in C++. This includes:
* a tool you've written
* a game you've been working on
* your first non-trivial C++ program
The rules of this thread are very straight forward:
* The project must involve C++ in some way.
* It must be something you (alone or with others) have done.
* Please share a link, if applicable.
* Please post images, if applicable.
If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.
Last month's thread: https://www.reddit.com/r/cpp/comments/1wwiz8g/c_show_and_tell_october_2026/
https://redd.it/1xo0gru
@r_cpp
Use this thread to share anything you've written in C++. This includes:
* a tool you've written
* a game you've been working on
* your first non-trivial C++ program
The rules of this thread are very straight forward:
* The project must involve C++ in some way.
* It must be something you (alone or with others) have done.
* Please share a link, if applicable.
* Please post images, if applicable.
If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.
Last month's thread: https://www.reddit.com/r/cpp/comments/1wwiz8g/c_show_and_tell_october_2026/
https://redd.it/1xo0gru
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
Dealing with AI Slop At Work
I work at a C++ shop with coders that I really respected - very deep C++ knowledge and are building very technical deep systems products. Over the last few months the CTO has gone off the deep end with AI talking of creating software factory (He’s been reading too much X), he releases huge multi thousand line PRs with basically no review. All sense of scientific temperament and engineering rigour has gone out of the window it seems.
I do believe that AI is a transformational tool and I use it plenty in the development process but I still strive to understand what the AI has written and often use the AI as multiplier rather than surrendering my thinking to it. it’s become increasingly hard to actually develop while deeply understanding the codebase because it has become so sloppy.
I am very sad as this means I’m not really interfacing with writing C++ as much and exploring cool new corners of the language in my daily work.
There is definitely some cool stuff this lets us do a bit more of - high level planning and systems design by reading many papers as well as exploring formal verification.
But overall I am left disappointed. I wonder how it is like at everyone else’s work places and if anyone has any thoughts and suggestions on how I can still develop my C++ knowledge.
https://redd.it/1xpshkh
@r_cpp
I work at a C++ shop with coders that I really respected - very deep C++ knowledge and are building very technical deep systems products. Over the last few months the CTO has gone off the deep end with AI talking of creating software factory (He’s been reading too much X), he releases huge multi thousand line PRs with basically no review. All sense of scientific temperament and engineering rigour has gone out of the window it seems.
I do believe that AI is a transformational tool and I use it plenty in the development process but I still strive to understand what the AI has written and often use the AI as multiplier rather than surrendering my thinking to it. it’s become increasingly hard to actually develop while deeply understanding the codebase because it has become so sloppy.
I am very sad as this means I’m not really interfacing with writing C++ as much and exploring cool new corners of the language in my daily work.
There is definitely some cool stuff this lets us do a bit more of - high level planning and systems design by reading many papers as well as exploring formal verification.
But overall I am left disappointed. I wonder how it is like at everyone else’s work places and if anyone has any thoughts and suggestions on how I can still develop my C++ knowledge.
https://redd.it/1xpshkh
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
clice 1.0: a C++ language server built on Clang, with C++20 modules out of the box, non-self-contained headers, and crash isolation
Hi r/cpp! I've been working on clice, a C++ language server built on Clang, for about two and a half years, and 1.0 is out today. The main differences from clangd:
- Every compile runs in a worker process, so a Clang crash costs one request instead of the whole server.
- C++20 modules work out of the box from a `compile_commands.json`, with PCHs and PCMs cached on disk across sessions.
- Non-self-contained headers are compiled in the context of a file that includes them, and you can switch contexts and build configurations.
- Template support: completion and go-to-implementation through dependent names, using instantiations when there are any.
- A CLI to index, query, refactor and modularize whole projects.
The post covers the features and the story behind it. Binaries for Linux, macOS and Windows (x64 and arm64) are on the release page, and the VS Code extension is on the Marketplace. Feedback and bug reports are very welcome!
Release post: https://ykiko.me/en/articles/2105384023094834022/
https://redd.it/1xwyk9n
@r_cpp
Hi r/cpp! I've been working on clice, a C++ language server built on Clang, for about two and a half years, and 1.0 is out today. The main differences from clangd:
- Every compile runs in a worker process, so a Clang crash costs one request instead of the whole server.
- C++20 modules work out of the box from a `compile_commands.json`, with PCHs and PCMs cached on disk across sessions.
- Non-self-contained headers are compiled in the context of a file that includes them, and you can switch contexts and build configurations.
- Template support: completion and go-to-implementation through dependent names, using instantiations when there are any.
- A CLI to index, query, refactor and modularize whole projects.
The post covers the features and the story behind it. Binaries for Linux, macOS and Windows (x64 and arm64) are on the release page, and the VS Code extension is on the Marketplace. Feedback and bug reports are very welcome!
Release post: https://ykiko.me/en/articles/2105384023094834022/
https://redd.it/1xwyk9n
@r_cpp
GitHub
Release v1.0.0 · clice-io/clice
The first stable release of clice, a C/C++ language server built on Clang, and the command line beside it that shares its configuration, caches and index. Documentation: https://docs.clice.io
The V...
The V...
Decoding base64 email attachments: a speed ranking of programming languages
https://lemire.me/blog/2026/11/20/decoding-base64-email-attachments/
https://redd.it/1y4dl62
@r_cpp
https://lemire.me/blog/2026/11/20/decoding-base64-email-attachments/
https://redd.it/1y4dl62
@r_cpp
Daniel Lemire's blog
Decoding base64 email attachments: a speed ranking of programming languages
Email attachments are base64. So are cryptographic PEM certificates. In both cases the text is broken into lines, 76 characters for email and 64 for PEM. Skipping line endings sounds trivial. Yet many fast decoders only work on uninterrupted base64. As soon…
Why does this return false even when cart has 3 items?
bool has_discount(const std::vector<int>& cart) {
int min_items = -1;
if (cart.size() > min_items) {
return true;
}
return false;
}
Under C++ usual arithmetic conversions, comparing unsigned std::size_t with signed int converts -1 to SIZE_MAX, so 3 > SIZE_MAX evaluates to false. Cleanest fix in C++20 is std::cmp_greater(cart.size(), min_items) or std::ssize(cart) > min_items.
Always wild how -Wall -Wextra catches this immediately, yet it still slips into live codebases and coding assessments all the time.
Spotted this in a daily C++ bug-spotting speedrun called Redline (3 short snippets a day against a clock) if anyone wants to try today's rounds: https://redline.playredline.workers.dev
https://redd.it/1y4flkr
@r_cpp
bool has_discount(const std::vector<int>& cart) {
int min_items = -1;
if (cart.size() > min_items) {
return true;
}
return false;
}
Under C++ usual arithmetic conversions, comparing unsigned std::size_t with signed int converts -1 to SIZE_MAX, so 3 > SIZE_MAX evaluates to false. Cleanest fix in C++20 is std::cmp_greater(cart.size(), min_items) or std::ssize(cart) > min_items.
Always wild how -Wall -Wextra catches this immediately, yet it still slips into live codebases and coding assessments all the time.
Spotted this in a daily C++ bug-spotting speedrun called Redline (3 short snippets a day against a clock) if anyone wants to try today's rounds: https://redline.playredline.workers.dev
https://redd.it/1y4flkr
@r_cpp
redline.playredline.workers.dev
REDLINE — Daily Bug-Spotting Speedrun
Spot the broken line, patch or diagnose why it fails, and beat the clock across 3 rounds in Python, C++, Java, or SQL.