Urgent.News

What's breaking now, across thousands of outlets.

Tech

C++26: #embed

The C++26 standard introduces a new preprocessor directive called #embed, which allows developers to integrate binary files directly into C++ programs without the need for external tools or custom scripts. This eliminates the common ritual of converting files into C arrays, wiring them into build systems, and praying that the conversion is not forgotten during updates.

#embed works by turning a file into a comma-separated sequence of integer constant expressions, directly at compile time. It eliminates the need for tools like xxd -i, objcopy, linker tricks, Python scripts, or CMake file(READ), which are fragile, platform-specific, and prone to becoming stale if not regenerated. The standardization process for #embed took over five years, with the first revision submitted in 2020 and fourteen revisions over five years before gaining committee approval.

The syntax of #embed is simple and straightforward. When used at its simplest, it reads a file (e.g., icon.png) and expands to a comma-separated list of integer constant expressions, one per byte. Each value ranges from 0 to 255, assuming CHAR_BIT == 8, which is true on all platforms that matter.

#embed offers four standard parameters, specified in parentheses after the resource identifier using a syntax borrowed from attributes. These parameters allow for fine-tuning the embedding process. They include:

- Limiting the number of bytes embedded (useful for pulling in just a file header, magic number, or fixed-size prefix)

- Prepending or appending token sequences (only when the resource is non-empty)

- Providing fallback content when the resource exists but has zero bytes

The preprocessor also includes a companion test, __has_embed, similar to __has_include from C++17. This test helps determine whether a resource exists and whether it has content before attempting to embed it. This feature is particularly useful when the resource might not exist in all build environments.

One of the advantages of #embed is that it embeds the resource directly into the source code, eliminating the need for build system attention or generated files. The compiler reads the resource, and the build system doesn't need to know about it, ensuring there's no sync risk between the resource and the binary.

GCC 15 has full support for #embed, while Clang 19+ supports it as a C23 extension in C++ mode (with -Wno-c23-extensions to suppress the warning). However, MSVC does not currently support #embed. Compiler Explorer allows testing #embed with various compilers, including GCC 15+ and a custom Clang build that has had support for years.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at sandordargo.com →

More in Tech

More from Wednesday 5 August →