Editorial changes were made to the paper. These changes are non-consequential:
Moved is_empty
examples to the proper OPTIONAL section.
Moved prefix
examples to the embed parameter wording sub-clause.
Added a history section explaining some of the pre-proposal steps this proposal went through to reach the form it is in today in §â¯6.1 Why a Preprocessor Directive, Specifically?.
Add the letter of support sent in to the C Standards and Shepherdâs Oasis, LLC in §â¯3.3 Support.
Additional syntax changes based on feedback from Joseph Myers, Hubert Tong, and users.
Minor wording tweaks and typo clean up.
An implementation available in Godbolt (since last revision as well and noted below).
The paperâs source code has been refactored:
Separated WG21 paper from WG14 paper.
Core paper together (rationale, reasoning), included in both C and C++ papers since rationale is identical.
Changed __has_embed
to match feedback from last standards meeting, nominally that an empty resource returns 2
instead of 1
(but both decay to a truthy value during preprocessor conditional inclusion expressions). Modified by the wording and the prose in §â¯4.4 __has_embed.
As a reaction to this, the is_empty
embed parameter is an optional part of the proposal, as explained in §â¯4.2.1.3 Empty Signifier. This did affect a user in an impactful manner but the new functionality is fine, but has some downsides w.r.t. "repeating yourself".
The wording for the limit parameter (in the embed parameter sub-clauses) adjusted to perform macro expansion, at least once. Exact wording may need help.
Clean up syntax.
Reimplement and deploy extension in Clang to ensure an implementation of named parameters work.
Change wording to encapsulate the new fixes.
Removed C++ wording to focus on C wording for this document.
Added post C meeting fixes to prepare for hopeful success next meeting.
Added 2 more examples to C and C++ wording.
Vastly improved wording and reduced ambiguities in syntax and semantics.
Fixed various wording issues.
Added post C++ meeting notes and discussion.
Removed type or bit specifications from the #embed
directive.
Moved "Type Flexibility" section and related notes to the Appendix as they are now unpursued.
Added post C meeting notes and discussion.
Added discussion of potential endianness.
Improved wording section at the end to be more detailed in handling preprocessor (which does not understand types).
Initial release! ð
The votes for the C Committee are as follows:
Y: Ye
N: Nay
A: Abstain
"Does WG14 want the embed parameter specification as shown in N2898?"
From the January/February 2022 Meeting Minutes, Summary of Decisions:
WG14 wants the embed parameter specification as shown in N2898.
We interpret this as consensus. We keep the parameters but make the one that folks were questioning ( is_empty
) optional in response to the feedback during and after the meeting.
"Do we want to allow #embed to appear in any context that is different from an initialization of a character array?"
"Leaning in the direction of no but not clear." The paper author after consideration chose to keep this as-is right now. Discussion of the feature meant that trying to ban this from different contexts meant that a naïve, separated-preprocessor implementation would be banned and it would require special compiler magic to diagnose. Others pointed out that just trying to leave it "unspecified whether it works outside of the initialization of an array or not" is very dangerous to portability. The author agrees with this assessment and therefore will leave it as-is. The goal of this feature is to enable implementers to use the magic if they so choose, as an implementation detail and a Quality of Implementation selling point. Vendors who provide a simple expansion may not see improvements to throughput and speed of translation but that is their choice as an implementer. Therefore, we cannot do anything which would require them or any preprocessor implementation to traffic in magic directives unless they want to.
2.3. April 2020 Virtual C Meeting"We want to have a proper preprocessor #embed ...
over a #pragma _STDC embed ...
-based directive."
This had UNANIMOUS CONSENT to pursue a proper preprocessor directive and NOT use the #pragma
syntax. It is noted that the author deems this to be the best decision!
The following poll was later superseded in the C and C++ Committees.
"We want to specify embed as using #embed [bits-per-element] header-name
rather than #embed [pp-tokens-for-type] header-name
." (2-way poll.)
Y: 10 bits-per-element (Ye)
N: 2 type-based (Nay)
A: 4 Abstain (Abstain)
This poll will be a bit harder to accommodate properly. Using a constant - expression
that produces a numeric constant means that the max-length specifier is now ambiguous. The syntax of the directive may need to change to accommodate further exploration.
For well over 40 years, people have been trying to plant data into executables for varying reasons. Whether it is to provide a base image with which to flash hardware in a hard reset, icons that get packaged with an application, or scripts that are intrinsically tied to the program at compilation time, there has always been a strong need to couple and ship binary data with an application.
Neither C nor C++ makes this easy for users to do, resulting in many individuals reaching for utilities such as xxd
, writing python scripts, or engaging in highly platform-specific linker calls to set up extern
variables pointing at their data. Each of these approaches come with benefits and drawbacks. For example, while working with the linker directly allows injection of very large amounts of data (5 MB and upwards), it does not allow accessing that data at any other point except runtime. Conversely, doing all of these things portably across systems and additionally maintaining the dependencies of all these resources and files in build systems both like and unlike make
is a tedious task.
Thusly, we propose a new preprocessor directive whose sole purpose is to be #include
, but for binary data: #embed
.
The reason this needs a new language feature is simple: current source-level encodings of "producing binary" to the compiler are incredibly inefficient both ergonomically and mechanically. Creating a brace-delimited list of numerics in C comes with baggage in the form of how numbers and lists are formatted. Câs preprocessor and the forcing of tokenization also forces an unavoidable cost to lexer and parser handling of values.
Therefore, using arrays with specific initialized values of any significant size becomes borderline impossible. One would think this old problem would be work-around-able in a succinct manner. Given how old this desire is (that comp.std.c thread is not even the oldest recorded feature request), proper solutions would have arisen. Unfortunately, that could not be farther from the truth. Even the compilers themselves suffer build time and memory usage degradation, as contributors to the LLVM compiler ran the gamut of the biggest problems that motivate this proposal in a matter of a week or two earlier this very year. Luke is not alone in his frustrations: developers all over suffer from the inability to include binary in their program quickly and perform exceptional gymnastics to get around the compilerâs inability to handle these cases.
C developer progress is impeded regarding the inability to handle this use case, and it leaves both old and new programmers wanting.
Finally, Microsoft has an ABI problem with its maximum string literal size that cannot be solved using string literals or anything treated like string literals, as the LLVM thread and the thread from Claire Xen make clear. It has also frustrated both C an C++ programmers alike, despite their best efforts. It was so frustrating that even extended-C-and-C++-compilers, like Circle, solve this problem with custom directives.
3.2. But How Expensive Is This?Many different options as opposed to this proposal were seriously evaluated. Implementations were attempted in at least 2 production-use compilers, and more in private. To give an idea of usage and size, here are results for various compilers on a machine with the following specification:
Intel Core i7 @ 2.60 GHz
24.0 GB RAM
Debian Sid or Windows 10
Method: Execute command hundreds of times, stare extremely hard at htop
/Task Manager
While time
and Measure - Command
work well for getting accurate timing information and can be run several times in a loop to produce a good average value, tracking memory consumption without intrusive efforts was much harder and thusly relied on OS reporting with fixed-interval probes. Memory usage is therefore approximate and may not represent the actual maximum of consumed memory. All of these are using the latest compiler built from source if available, or the latest technology preview if available. Optimizations at - O2
(GCC & Clang style)/ / O2 / Ob2
(MSVC style) or equivalent were employed to generate the final executable.
#embed
GCC 0.236 s 0.231 s 0.300 s 1.069 s xxd
-generated GCC 0.406 s 2.135 s 23.567 s 225.290 s xxd
-generated Clang 0.366 s 1.063 s 8.309 s 83.250 s xxd
-generated MSVC 0.552 s 3.806 s 52.397 s Out of Memory 3.2.2. Memory Size Strategy 40 kilobytes 400 kilobytes 4 megabytes 40 megabytes #embed
GCC 17.26 MB 17.96 MB 53.42 MB 341.72 MB xxd
-generated GCC 24.85 MB 134.34 MB 1,347.00 MB 12,622.00 MB xxd
-generated Clang 41.83 MB 103.76 MB 718.00 MB 7,116.00 MB xxd
-generated MSVC ~48.60 MB ~477.30 MB ~5,280.00 MB Out of Memory 3.2.3. Analysis
The numbers here are not reassuring that compiler developers can reduce the memory and compilation time burdens with regard to large initializer lists. Furthermore, privately owned compilers and other static analysis tools perform almost exponentially worse here, taking vastly more memory and thrashing CPUs to 100% for several minutes (to sometimes several hours if e.g. the Swap is engaged due to lack of main memory). Every compiler must always consume a certain amount of memory in a relationship directly linear to the number of tokens produced. After that, it is largely implementation-dependent what happens to the data.
The GNU Compiler Collection (GCC) uses a tree representation and has many places where it spawns extra "garbage", as its called in the various bug reports and work items from implementers. There has been a 16+ year effort on the part of GCC to reduce its memory usage and speed up initializers (C Bug Report and C++ Bug Report). Significant improvements have been made and there is plenty of room for GCC to improve here with respect to compiler and memory size. Somewhat unfortunately, one of the current changes in flight for GCC is the removal of all location information beyond the 256th initializer of large arrays in order to save on space. This technique is not viable for static analysis compilers that promise to recreate source code exactly as was written, and therefore discarding location or token information for large initializers is not a viable cross-implementation strategy.
LLVMâs Clang, on the other hand, is much more optimized. They maintain a much better scaling and ratio but still suffer the pain of their token overhead and Abstract Syntax Tree representation, though to a much lesser degree than GCC. A bug report was filed but talk from two prominent LLVM/Clang developers made it clear that optimizing things any further would require an extremely large refactor of parser internals with a lot of added functionality, with potentially dubious gains. As part of this proposal, the implementation provided does attempt to do some of these optimizations, and follows some of the work done in this post to try and prove memory and file size savings. (The savings in trying to optimize parsing large array literals were "around 10%", compared to the order-of-magnitude gains from #embed
and similar techniques).
Microsoft Visual C (MSVC) scales the worst of all the compilers, even when given the benefit of being on its native operating system. Both Clang and GCC outperform MSVC on Windows 10 or WINE as of the time of writing.
Linker tricks on all platforms perform better with time (though slower than #embed
implementation), but force the data to be optimizer-opaque (even on the most aggressive "Link Time Optimization" or "Whole Program Optimization" modes compilers had). Linker tricks are also exceptionally non-portable: whether it is the incbin
assembly command supported by certain compilers, specific invocations of rc . exe
/ objcopy
or others, non-portability plagues their usefulness in writing Cross-Platform C (see Appendix for listing of techniques). This makes C decidedly unlike the "portable assembler" advertised by its proponents (and my Professors and co-workers).
To say that #embed
enjoys broad C Community support is an understatement. In all the years we have written proposals for C and C++, this is the only one where someone physically mailed us a letter - from a different country - directly to the Standards Body to try and make a case for the feature directly, rather than what was already in the paper:
This is just one of hundreds of messages sent over time digitally, with participants from everywhere in the European Union (France, Germany, Spain, Czech Republic, Switzerland, Denmark, etc.) to East and Southern Asia (China, Japan, Vietnam, etc.) and many, many more from North and South America (including Canada, Brazil, Argentina, etc.). There has been a clear and present need to solve this problem for quite some time now.
4. DesignThere are two design goals at play here, sculpted to specifically cover industry standard practices with build systems and C programs.
The first is to enable developers to get binary content quickly and easily into their applications. This can be icons/images, scripts, tiny sound effects, hardcoded firmware binaries, and more. In order to support this use case, this feature was designed for simplicity and builds upon widespread existing practice.
The second is extensibility. We recognize that talking to arbitrary places on either the file system, network, or similar has different requirements. After feedback from an implementer about syntax for extensions, we reached out to various users of the beta builds or custom builds using #embed
-like things. It turns out many of them have needs that, since they are the ones building and in some cases patching over/maintaining their compiler, have needs for extensible attributes that can be passed to #embed
directives. Therefore, we structured the syntax in a way that is favorable to "simple" scanning tools but powerful enough to handle arbitrary directives and future extension points.
Providing a directive that mirrors #include
makes it natural and easy to understand and use this new directive. It accepts both chevron-delimited ( <>
) and quote-delimited ( ""
) strings like #include
does. This matches the way people have been generating files to #include
in their programs, libraries and applications: matching the semantics here preserves the same mental model. This makes it easy to teach and use, since it follows the same principles:
/* default is unsigned char */ const unsigned char icon_display_data[] = { #embed "art.png" }; /* specify any type which can be initialized form integer constant expressions will do */ const char reset_blob[] = { #embed "data.bin" };
Because of its design, it also lends itself to being usable in a wide variety of contexts and with a wide variety of vendor extensions. For example:
/* attributes work just as well */ const signed char aligned_data_str[] __attribute__ ((aligned (8))) = { #embed "attributes.xml" };
The above code obeys the alignment requirements for an implementation that understands GCC directives, without needing to add special support in the #embed
directive for it: it is just another array initializer, like everything else.
It follows the same implementation experience guidelines as #include
by leaving the search paths implementation defined, with the understanding that implementations are not monsters and will generally provide - fembed - path
/ - fembed - path =
and other related flags as their users require for their systems. This gives implementers the space they need to serve the needs of their constituency.
Build systems today understand the make dependency format, typically through use of the compiler flags - ( M ) MD
and friends. This sees widespread support, from CMake, Meson and Bazel to ninja and make. Even VC++ has a version of this flag -- / showIncludes
-- that gets parsed by build systems.
This preprocessor directive fits perfectly into existing build architecture by being discoverable in the same way with the same tooling formats. It also blends perfectly with existing distributed build systems which preprocess their files with - frewrite - includes
before sending it up to the build farm, as distcc
and icecc
do.
The syntax for this feature is for an extensible preprocessor directive. The general form is:
# embed <header-name>|"header-name" parameters...
where parameters
refers to the syntax of no_arg
/ with_arg ( values , ...)
/ vendor :: no_arg
/ vendor :: with_arg ( tokens ...)
that is already part of the grammar. The syntax takes after many existing extensions in many preprocessor implementations and specifications, including OpenMP, Clang #pragma
s, Microsoft #pragma
s, and more. The named parameters was a recommendation by an implementer
This syntax keeps the header-name, enclosed in angle brackets or quotation marks, first to allow a "simple" preprocessing tool to quickly scan for all the necessary dependency names without having to parse any of the names or parameters that come after. Both standard names and vendor/implementation-specific names can also be accommodated in the list of naked attributes, allowing for specific vendor extensions in a consistent manner while the standard can take the normal foo
names.
One of the things thatâs critical about #embed
is that, because it works with binary resources, those resources have characteristics very much different from source and header files present in a typical filesystem. There may be need for authentication (possibly networked), permission, access, additional processing (new-line normalization), and more that can be somewhat similarly specified through the implementation-defined parameters already available through the C and C++ Standards' " fopen
" function.
However, adding a "mode" string similar to fopen
, while extensible, is archaic and hard to check. Therefore, the syntax allows for multiple "named expressions", encapsulated in parentheses, and marked with ::
as a form of "namespacing" identifiers similar to [[ vendor :: attr ]]
attribute-style syntax. However, parameters do not have the balanced square bracket [[]]
delimiters, and just use the vendor :: attr
form with an optional parentheses-enclosed list of arguments.
Some example attributes including interpreting the binary data as "text" rather than a bitstream with clang :: text ( utf -8 )
, providing authenticated access with fs :: auth ( "username" , "password" )
, yosys :: type ( hardware_entry )
to change the element of each entry produced, and more. These are all things vendors have indicated they might support for their use cases.
The earliest adopters and testers of the implementation reported problems when trying to access POSIX-style char
devices and pseudo-files that do not have a logical limitation. These "infinity files" served as the motivation for introducing the "limit" parameter; there are a number of resources which are logically infinite and thusly having a compiler read all of the data would result an Out of Memory error, much like with #include
if someone did #include "/dev/urandom"
.
The limit parameter is specified after the resource name in #embed
, like so:
const int please_dont_oom_kill_me[] = { #embed "/dev/urandom" limit(512) };
This prevents locking compilers in an infinite loop of reading from potentially limitless resources. Note the parameter is a hard upper bound, and not an exact requirement. A resource may expand to a 16-element list rather than a 512-element list, and that is entirely expected behavior. The limit is the number of elements allowed up to the maximum for this type.
This does not provide a form of "timeout" for e.g. resources stored on a Network File System or an inactivity limit or similar. Implementations that utilize support for more robust handling of resource location schemes like Uniform Resource Identifiers (URIs) that may interface with resources that take extensive amounts of time to locate should provide implementation-defined extensions for timeout or inactivity checks.
4.2.1.2. Non-Empty Prefix and SuffixSomething pointed out by others using this preprocessor directive is a problem similar to __VA_ARGS__
: when placing this parameter with other tokens before or after the #embed
directive, it sometimes made it hard to properly anticipate whether a file was empty or not.
The #embed
proposal includes a prefix and suffix entry that applies if and only if the resource is non-empty:
const unsigned char null_terminated_file_data[] = { #embed "might_be_empty.txt" \ prefix(0xEF, 0xBB, 0xBF, ) /* UTF-8 BOM */ \ suffix(,) 0 // always null-terminated };
prefix
and suffix
only work if the #embed
resource is not empty. If a user wants a prefix or suffix that appears unconditionally, they can simply just type the tokens they want before and after: there is nothing to be gained from adding a standards-mandated prefix and suffix that works in both the empty and non-empty case.
This is for the case when the given resource exists, but it is empty. This allows a user to have a sequence of tokens between the parentheses passed to the is_empty
parameter here: #embed "blah" is_empty(SPECIAL_EMPTY_MARKER MORE TOKENS)
.
If "blah"
exists but is empty, this will replace the directive with the (potentially macro expanded) contents between the parentheses of the is_empty
parameter. This can also be combined with a limit ( 0 )
parameter to always have the is_empty
token return. This can be useful for macro-expanded integer constant expressions that may end up being 0.
An example program single - urandom . c
:
int main () { #define SOME_CONSTANT 0 return #embed </dev/urandom> is_empty(0) limit(SOME_CONSTANT) ; }
This program will expand to the equivalent of int main () { return 0 ; }
if SOME_CONSTANT
is 0, or a single (random) unsigned char
value if it is 1. (If SOME_CONSTANT
is greater than 1, it produces a comma-delimited list of integers, which gets treated as a sequence to the comma operator after the return
keyword. Some compilers warn about the left-hand operands having no effect.)
Previously, this was the only way to detect that the resource was empty. This functionality can be substituted with having to use __has_embed ( ⦠)
with the same contents and specifically check for the return value of == 2
. While this change create some repeating-yourself friction in the identifier, there was only 1 user who actually needed the is_empty signifier, and that was only because they were using it to replace it with a very particularly sized and shaped data array. The __has_embed
technique worked just fine for them as well at the cost of some repetition (to check for embed parameters), and after some discussion with the user it was deemed okay to switch to this syntax, since during the discusison of #embed
in the January/February 2022 WG14 C Standards Committee Meeting it was commented on that there were too many signifiers.
We do not want to entirely lose that userâs use case, however, so we have made the is_empty
parameter an optional part of the wording, to be voted on as a separate piece.
Both C and C++ compilers have rich constant folding capabilities. While C compilers only acknowledge a fraction of what is possible by larger implementations like MSVC, Clang, and GCC, C++ has an entire built-in compile-time programming bit, called constexpr
. Most typical solutions cannot be used as constant expressions because they are hidden behind run-time or link-time mechanisms ( objcopy
, or the resource compiler rc . exe
on Windows, or the static library archiving tools). This means that many algorithms and data components which could strongly benefit from having direct access to the values of the integer constants do not because the compiler cannot "see" the data, or because Whole Program Optimization cannot be aggressive enough to do anything with those values at that point in the compilation (i.e., during the final linking stage).
This makes #embed
especially powerful, since it guarantees these values are available as-if it was written by as a sequence of integers whose values fit within an unsigned char
.
__has_embed
C and C++ are support a __has_include
. It makes sense to have an analogous __has_embed
identifier. It can take a __has_embed ( "header-name" ... )
or __has_embed ( < header - name > ... )
resource name identifier, as well as additional arguments to let vendors pass in any additional arguments they need to properly access the file (following the same attribute-like parameters passed to the directive). __has_embed
evaluates to:
0
if the reesource is not found or any parameter in the embed - parameter - list
does not exist; or,
1
if the resource is found, it is not empty, and the embed - parameter - list
(including the vendor-specific ones) are supported; or,
2
if the resource is found, it is empty, and the embed - parameter - list
(including the vendor-specific ones) are supported.
This may raise questions of "TOCTTOU" (Time of Check to Time of Use) problems, but we already have these problems between __has_include
and #include
. They are also already solved by existing implementations. For example, the LLVM/Clang compiler uses FileManager
and SourceManager
abstractions which cache files. GCCâs "libcpp" will cache already-opened files (up to a limit). Any TOCTTOU problems have already been managed and provided for using the current #include
infrastructure of these compilers, and if any compiler wants a more streamlined and consistent experience they should deploy whatever Quality of Implementation (QoI) they see fit to achieve that goal.
Finally, note that this directive DOES expand to 0
if a given parameters that the implementation does not support. This makes it easier to determine if a given vendor-specific embed directive is supported. In fact, support can be checked in most cases by using a combination of __FILE__
and __has_embed
:
int main () { #if __has_embed (__FILE__ clang::element_type(short)) // load "short" values directly from memory short meow[] = { #embed "bits.bin" clang::element_type(short) }; #else // no support for implementation-specifid // clang::element_type parameter unsigned char meow_bytes[] = { #embed "bits.bin" }; unsigned short meow[] = { /* parse meow_bytes into short values by-hand! */ }; #endif return 0; }
For the C proposal, the wording for __has_embed (...)
returning 2
is optional, as it depends on whether or not the C Committee would like to solve this problem in one specific direction or another.
What would happen if you did
fread
into anint
?thatâs my answer ð
â Isabella Muerte
Itâs a simple answer. While we may not be reading into int
, the idea here is that the interpretation of the directive is meant to get as close to directly copying the bitstream, as is possible. A compiler-magic based implementation like the ones provided as part of this paper have no endianness issues, but an implementation which writes out integer literals may need to be careful of host vs. target endianness to make sure it serializes correctly to the final binary. As a litmus test, the following code -- given a suitably sized "foo.bin"
resource -- should return 0
:
#include <cstdio> #include <cstring> int main() { const unsigned char foo0[] = { #embed "foo.bin" }; const unsigned char foo1[sizeof(foo0)]; std::FILE* fp = std::fopen("foo.bin"); if (fp == nullptr) { return 1; } std::size_t foo1_read = std::fread(foo1, 1, sizeof(foo1), fp); if (foo1_read != sizeof(foo1)) { return 1; } if (memcmp(&foo0[0], &foo1[0], sizeof(foo0)) != 0) { return 1; } return 0; }
If the same file during both translation and execution, "foo.bin"
, is used here, this program should always return 0
. This is what the wording below attempts to achieve. Note that this is always a concern already, due to CHAR_BIT
and other target environment-specific variables that already exist; implementations have always been responsible for handling differences between the host and the target and this directive is no different. If the CHAR_BIT
of the host vs. the target is the same, then the directive is more simple. If it is not, then an implementation will have to perform translation.
An implementation of this functionality is available in branches of both GCC and Clang, accessible right now with an internet connection through the online utility Compiler Explorer. The Clang compiler with this functionality is called "x86-64 clang (thephd.dev)" in the Compiler Explorer UI:
int main () { return #embed </dev/urandom> limit(1) ; }6. Alternative Syntax
There were previous concerns about the syntax using pragma-like syntax and more. WG14 voted to keep the syntax as a plain #embed
preprocessor directive, unanimously.
Previously, different syntax was used to specify the limit and other kinds of parameters. These have been normalized to be a suffix of attribute-like parameters, at the request of an implementer and the C++ Standards Committee discussion of the paper in June 2021. It has had hugely positive feedback and users have reported the new syntax to be clearer, while other implementers have stated this is much better for them and the platforms for which they intend to add additional embed parameters.
6.1. Why a Preprocessor Directive, Specifically?Although the reasoning is scattered around the paper, it may be illuminating to explain the full "etymology" of the preprocessor directive of #embed
and why it came to be. Originally, #embed
was conceived not by the authors of this paper, but as a C++ feature (potentially portable to C) using a String Literal of the form F "file.ext"
or bF "file.ext"
. This proposal was soundly rejected by WG21, despite having one of the strongest champions it could possibly have presenting it (the original author of the paper could not make Committee Meetings). There was much confusion about whether or not this functionality would include a null terminator (some argued "yes", because it was the form of a string literal; others argued "no"). There was also the confusion between what it meant to include the file as a "text" file versus a "binary" file (the F ""
versus bF ""
prefixes). Furthermore, there was the question of what kind of data would come out on the other side ( char
for "text" data, unsigned char
for binary?).
From there, the authors of this paper worked to explore a new version that was, effectively, language magic. This was done because, very long ago, solutions around doing #include_binary
or similar were (colloquially) rejected from both WG21 and WG14, with various different reasons. This is where the C++-shaped std :: embed ( "file.ext" )
came from, and forms the basis of the C++ proposal [p1040r6]. It was meant to be filled in using either directly compiler-based language magic such as a builtin (like __builtin_embed
), or using compiler-specific extensions such as . incbin
([incbin]) but mightily improved to be usable as a constant expression. This approach found great traction until tool vendors and tool developers within compiler groups complained that such a construct - especially in C++ - would allow evaluation of more than just String Literals as the entry into std :: embed
. This is partly a feature, as it meant that reading a file and pulling file names from it could reuse the included data to then feed it back into the magic directive to read another file, resulting in the ability to parse e.g. GLSL shader files or JSON files which referenced other JSON files into read-only, compiled memory. Unfortunately, such ability means that it is beyond the Phase 1-5, preprocessor abilities of C and C++ compilers, and dependencies must be computed at what is typically known as "Semantic Analysis" time in compilers.
This also proved problematic for tool developers outside of the C++ Standards Committee. Correspondence with Henry Miller of the icecc (distributed build tool) development list over e-mail revealed that while he would be comfortable just having a loosely-based "best effort" approach to finding file names from any std :: embed ( "..." )
function call. He indicated some preference for a more static version that could allow him to find all potentially-included files without any risk of false-positives or other issues, that a simple tool like icecc could handle.
This is where #embed
was conceived. While it loses the ability to be used recursively with itself like the language-magic version in C++, it retains the following important qualities for all stakeholders involved:
the directive can be read using basic preprocessing tools;
the directive has parameters that come after the core #embed "file.txt"
part, which means current infrastructure around parsing similar #include
files is retained;
the directive does not need any information or computation from beyond Phase 4 of compilation; and,
the directive does not have any questions of "encoding" or "null termination" like the File String Literals proposal.
This is the version that stayed in development since around late 2018, and has been continuously iterated over. The syntax was changed once, to accommodate the trailing parameter list, as suggested by both compiler developers and end-users several times during the course of its development. The trailing parameter list was also the most powerful way to allow compiler extensions that did special behaviors, as it was incredibly clear that many vendors had extensions for data, attributes for variables, and more they wanted to feed into #embed
and the various types it initialized. It took some time to smith the wording into the form that works best, but importantly the wording from the beginning had the following two goals in mind:
a low-effort quality of implementation would still work validly in all places it could conceivably be used (which is anywhere, since itâs a preprocessor directive); and,
a high-effort quality of implementation could significantly speed up the inclusion of binary resources in a program.
Notably, the first was important for users. They did not want something that would only be conditionally supported. The latter is important for both users and vendors: Microsoft needs a way to get out of its String Literal Maximum Limit ABI problems and a way to store data quickly, as every other compiler even on its preferred platform (Windows 7, 8, 8.1, and 10) are outperformed by other compilers simply initializing data arrays in a big, brace-delimited array. In order to solve for the bug reports talked about earlier ([nonius-visual-c-error], [llvm-string-init-fail], [gcc-large-init-bug-c], and more) vendors need the capability to provide a fast built-in or internal token implementation for speed purposes. This has been validated by implementation efforts outside of the authors here, in the QAC Compiler by Alex Gilding. With the authors currently privately and publicly supporting implementations of #embed
, Sean Baxterâs own implementation of embed styled slightly differently for the Circle compiler, and the implementation work by Alex, that brings us to 4 compilers (Clang, GCC, Circle, QAC) - private and commercially available - with experience and reported order-of-magnitude (and in some cases, two orders-of-magnitude) improvements on compilation and loading speed of data arrays previously stored in a variety of other manners, including linkers.
It is a long-battled, well-storied work of shared and community effort to solve a long-standing problem for C and C++. It gives vendors a way out of having to write increasingly integer-list-initialization-specific optimized parsers, and lets users connect C to the best binary and storage compression system they already know how to use with their existing implementations: the filesystem. It also prevents low-effort quality of implementations from being excluded from the feature set, making it feasible even for compilers such as the famous 8cc hobby compiler.
This is why #embed
is in the form it has ultimately ended up in.
This wording is relative to Câs latest working draft.
Editorâs Note: The ⨠characters are intentional. They represent stand-ins to be replaced by the editor.
7.1. Modify 6.4, paragraph 47.2. Add another control-line production to §6.10 Preprocessing Directives, Syntax, paragraph 1 and a new paragraph for the SemanticsIf the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token. There is one exception to this rule: header name preprocessing tokens are recognized only within
#include
preprocessing directives, in__has_include
expressions, and in implementation-defined locations within #pragma directives. header name preprocessing tokens are recognized only within#include
and#embed
preprocessing directives, in__has_include
and__has_embed
expressions, as well as in implementation-defined locations within#pragma
directives. In such contexts, a sequence of characters that could be either a header name or a string literal is recognized as the former.
control-line:7.3. Modify §6.10.1 Conditional inclusion to include a new "has-embed-expression" production by modifying paragraph 1, then modify the following paragraphs:
â¦
- # embed pp-tokens new-line
â¦
pp-attribute:
attribute-token pp-attribute-argument-clauseopt
pp-attribute-argument-clause:
( pp-balanced-token-sequenceopt )
pp-balanced-token-sequence:
pp-balanced-token
pp-balanced-token-sequence pp-balanced-token
pp-balanced-token:
( pp-balanced-token-sequenceopt )
[ pp-balanced-token-sequenceopt ]
{ pp-balanced-token-sequenceopt }
any preprocessing-token other than a parenthesis, a bracket, or a brace
embed-parameter-list:
pp-attribute
embed-parameter-list pp-attribute
â¦
Description
Some preprocessing directives take additional information by the use of a preprocessor attribute token (pp-attribute), which can either be an preprocessor attribute prefixed token (for implementation-specified preprocessor attributes) or a preprocessor standard attribute (for pp-attributes specified by this document).
In all aspects, a preprocessor standard attribute specified by this document as an identifier
pp_attr
and an identifier of the form__pp_attr__
shall behave the same when used as a preprocessor attribute token. except for the spelling.Constraints
â¦
7.4. Add a new sub-clause as §6.10.⨠to §6.10 Preprocessing Directives, preferably after §6.10.2 Source file inclusionSyntax
â¦
has-include-expression:
__has_include ( header-name )
__has_include ( header-name-tokens )
has-embed-expression:
__has_embed ( header-name embed-parameter-listopt )
__has_embed ( header-name-tokens embed-parameter-listopt )
â¦
The expression that controls conditional inclusion shall be an integer constant expression except that: identifiers (including those lexically identical to keywords) are interpreted as described below and it may contain zero or more defined macro expressions, has_include expressions, has_embed expressions, and/or has_c_attribute expressions as unary operator expressions.
â¦
The second forms of the has_include expression and has_embed expression are considered only if the first form does not match, in which case the preprocessing tokens are processed just as in normal text.
â¦
The resource (6.10.â¨) identified by the header-name preprocessing token sequence in each contained has_embed expression is searched for as if those preprocessing token were the pp-tokens in a
#embed
directive, except that no further macro expansion is performed. Such a directive shall satisfy the syntactic requirements of a#embed
directive. The has_embed expression evaluates to:
â 0 if the search fails or if any of the embed parameters in the embed parameter list specified are not supported by the implementation for the
#embed
directive; or,â 1 if the search for the resource succeeds and all embed parameters in the embed parameter list specified are supported by the implementation for the
#embed
directive.â¦
Semantics
The
#ifdef
,#ifndef
,#elifdef
, and#elifndef
, and the defined conditional inclusion operator, shall treat__has_include
,__has_embed
, and__has_c_attribute
as if they were the name of defined macros. The identifiers__has_include
,__has_embed
, and__has_c_attribute
shall not appear in any context not mentioned in this subclause.â¦
EXAMPLE: A combination of__FILE__
(6.10.8.1) and__has_embed
could be used to check for support of specific implementation extensions for the#embed
directiveâs parameters.#if __has_embed(__FILE__ ext::token(0xB055)) #define DESCRIPTION "Supports extended token embed" #else #define DESCRIPTION "Does not support extended token embed" #endifEXAMPLE: The below snippet uses__has_embed
to check for support of a specific implementation-defined embed parameter, and otherwise uses standard behavior to produce the same effect.void parse_into_s(short* ptr, unsigned char* ptr_bytes, unsigned long long size); int main () { #if __has_embed ("bits.bin" ds9000::element_type(short)) /* Implementation extension: create short integers from the */ /* translation environment resource into */ /* a sequence of integer constants */ short meow[] = { #embed "bits.bin" ds9000::element_type(short) }; #elif __has_embed ("bits.bin") /* no support for implementation-specific */ /* ds9000::element_type(short) parameter */ const unsigned char meow_bytes[] = { #embed "bits.bin" }; short meow[sizeof(meow_bytes) / sizeof(short)] = {}; /* parse meow_bytes into short values by-hand! */ parse_into_s(meow, meow_bytes, sizeof(meow_bytes)); #else #error "cannot find bits.bin resource" #endif return (int)(meow[0] + meow[(sizeof(meow) / sizeof(*meow)) - 1]); }â¦
Forward references: ⦠Mandatory macros (6.10.8.1) â¦
7.5. Add 3 new sub-clauses as §6.10.â¨.1 through §6.10.â¨.3, under §6.10.⨠Binary resource inclusionDescription
A resource is a source of data accessible from the translation environment. An embed parameter is a single attribute in the embed parameter list. It has an implementation resource width, which is the implementation-defined size in bits of the located resource. It also has a resource width, which is either:
â the number of bits as computed from the optionally-provided
limit
embed parameter (6.10.â¨.1), if present; or,â the implementation resource width.
An embed parameter list is a whitespace-delimited list of attributes which may modify the result of the replacement for the
#embed
preprocessing directive.Constraints
An
#embed
directive shall identify a resource that can be processed by the implementation as a binary data sequence given the provided embed parameters.Embed parameters not specified in this document shall be implementation-defined. Implementation-defined embed parameters may change the below-defined semantics of the directive; otherwise,
#embed
directives which do not contain implementation-defined embed parameters shall behave as described in this document.A resource is considered empty when its resource width is zero.
Let embed element width be either:
â an integer constant expression greater than zero determined by an implementation-defined embed parameter; or,
â
CHAR_BIT
.The result of
( resource width ) % ( embed element width )
shall be zero.Semantics
The expansion of a
#embed
directive is a token sequence formed from the list of integer constant expressions described below. The group of tokens for each integer constant expression in the list is separated in the token sequence from the group of tokens for the previous integer constant expression in the list by a comma. The sequence neither begins nor ends in a comma. If the list of integer constant expressions is empty, the token sequence is empty. The directive is replaced by its expansion and, with the presence of certain embed parameters, additional or replacement token sequences.A preprocessing directive of the form
# embed < h-char-sequence
<
embed-parameter-listopt new-linesearches a sequence of implementation-defined places for a resource identified uniquely by the specified sequence between the
<
and>
. The search for the named resource is done in an implementation-defined manner.A preprocessing directive of the form
# embed " q-char-sequence " embed-parameter-listopt new-line
searches a sequence of implementation-defined places for a resource identified uniquely by the specified sequence between the
"
delimiters. The search for the named resource is done in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read
# embed
<
h-char-sequence>
embed-parameter-listopt new-linewith the identical contained q-char-sequence (including
>
characters, if any) from the original directive.Either form of the
#embed
directive specified previously behave as specified below. The values of the integer constant expressions in the expanded sequence is determined by an implementation-defined mapping of the resourceâs data. Each integer constant expressionâs value is in the range from0
to( 2 embed element width ) - 1
, inclusive.If the list of integer constant expressions:
â is used to initialize an array of a type compatible with
unsigned char
, or compatible withchar
ifchar
cannot hold negative values; and,â the embed element width is equal to
CHAR_BIT
(5.2.4.2.1),then the contents of the initialized elements of the array are as-if the resourceâs binary data was
fread
into the array at translation time.A preprocessing directive of the form
# embed pp-tokens new-line
(that does not match one of the two previous forms) is permitted. The preprocessing tokens after embed in the directive are processed just as in normal text. (Each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens.) The directive resulting after all replacements shall match one of the two previous forms. The method by which a sequence of preprocessing tokens between a
<
and a>
preprocessing token pair or a pair of"
characters is combined into a single resource name preprocessing token is implementation-defined.An embed parameter with an attribute token that is one of the following is a standard embed parameter:
limit
â â â âprefix
â â â âsuffix
The significance of these attribute tokens is specified below.
This constraint helps ensure data is neither filled with padding values nor truncated in a given environment, and helps ensure the data is portable with respect to usages of
memcpy
with character type arrays initialized from the data.For example, an embed element width of 8 will yield a range of values from 0 to 255, inclusive.
Note that adjacent string literals are not concatenated into a single string literal (see the translation phases in 5.1.1.2); thus, an expansion that results in two string literals is an invalid directive.
Recommended Practice
The
#embed
directive is meant to translate binary data in resources to sequence of integer constant expressions in a way that preserves the value of the resourceâs bit stream where possible.Implementations should take into account translation-time bit and byte orders as well as execution time bit and byte orders to more appropriately represent the resourceâs binary data from the directive. This maximizes the chance that, if the resource referenced at translation time through the
#embed
directive is the same one accessed through execution-time means, the data that is e.g.fread
or similar into contiguous storage will compare bit-for-bit equal to an array of character type initialized from an#embed
directiveâs expanded contents.Implementations are encouraged to diagnose embed parameters that they do not process or understand, with the understanding that
__has_embed
may be used to check if an implementation supports a given embed parameter.EXAMPLE Placing a small image resource.
#include <stddef.h> void have_you_any_wool(const unsigned char*, size_t); int main (int, char*[]) { static const unsigned char baa_baa[] = { #embed "black_sheep.ico" }; have_you_any_wool(baa_baa, sizeof(baa_baa)); return 0; }EXAMPLE This snippet:
int main (int, char*[]) { static const unsigned char coefficients[] = { #embed "only_8_bits.bin" // potential constraint violation }; return 0; }may violate the constraint that
( resource width ) % ( embed element width )
must be 0. The 8 bits might not be evenly divisible by the embed element width (e.g., on a system whereCHAR_BIT
is 16). Issuing a diagnostic in this case may aid in portability by calling attention to potentially incompatible expectations between implementations and their resources.EXAMPLE Initialization of non-arrays.
int main () { /* Braces may be kept or elided as per normal initialization rules */ int i = { #embed "i.dat" }; /* i value is [0, 2^(embed element width)) first entry */ int i2 = #embed "i.dat" ; /* valid if i.dat produces 1 value, i2 value is [0, 2^(embed element width)) */ struct s { double a, b, c; struct { double e, f, g; }; double h, i, j; }; struct s x = { /* initializes each element in order according to initialization rules with comma-separated list of integer constant expressions inside of braces */ #embed "s.dat" }; return 0; }Non-array types can still be initialized since the directive produces a comma-delimited lists of integer constant expressions, a single integer constant expression, or nothing.EXAMPLE Equivalency of bit sequence and bit order between a translation-time read and an execution-time read of the same resource/file.
#include <string.h> #include <stddef.h> #include <stdio.h> int main() { static const unsigned char embed_data[] = { #embed <data.dat> }; const size_t f_size = sizeof(embed_data); unsigned char f_data[f_size]; FILE* f_source = fopen("data.dat", "rb"); if (f_source == NULL); return 1; char* f_ptr = (char*)&f_data[0]; if (fread(f_ptr, 1, f_size, f_source) != f_size) { fclose(f_source); return 1; } fclose(f_source); int is_same = memcmp(&embed_data[0], f_ptr, f_size); // if both operations refers to the same resource/file at // execution time and translation time, "is_same" should be 0 return is_same == 0 ? 0 : 1; }
7.6. OPTIONAL Modify §6.10.1 Conditional inclusion forConstraints
It may appear zero times or one time in the embed parameter list. Its attribute argument clause shall be present and have the form:
( constant-expression )
and shall be an integer constant expression. The integer constant expression shall not evaluate to a value less than 0.
The token
defined
shall not appear within the pp-balanced-token-sequence.Semantics
The embed parameter with an attribute token
limit
denotes a balanced preprocessing token sequence that will be used to compute the resource width. Independently of any macro replacement done previously (e.g. when matching the form of#embed
), the constant expression is evaluated after the balanced preprocessing token sequence is processed as in normal text, using the rules specified for conditional inclusion (6.10.1), with the exception that any defined macro expressions are not permitted.The resource width is:
â 0, if the integer constant expression evaluates to 0; or,
â the implementation resource width if it is less than the embed element width multiplied by the integer constant expression; or,
â the embed element width multiplied by the integer constant expression, if it is less than or equal to the implementation resource width.
EXAMPLE Checking the first 4 elements of a sound resource.
#include <assert.h> int main (int, char*[]) { static const char sound_signature[] = { #embed <sdk/jump.wav> limit(2+2) }; static_assert((sizeof(sound_signature) / sizeof(*sound_signature)) == 4, "There should only be 4 elements in this array."); // verify PCM WAV resource assert(sound_signature[0] == 'R'); assert(sound_signature[1] == 'I'); assert(sound_signature[2] == 'F'); assert(sound_signature[3] == 'F'); assert(sizeof(sound_signature) == 4); return 0; }EXAMPLE Similar to a previous example, except it illustrates macro expansion specifically done for the
limit ( ⦠)
parameter.#include <assert.h> #define TWO_PLUS_TWO 2+2 int main (int, char*[]) { const char sound_signature[] = { /* the token sequence within the parentheses for the "limit" parameter undergoes macro expansion, at least once, resulting in #embed <sdk/jump.wav> limit(2+2) */ #embed <sdk/jump.wav> limit(TWO_PLUS_TWO) }; static_assert((sizeof(sound_signature) / sizeof(*sound_signature)) == 4, "There should only be 4 elements in this array."); // verify PCM WAV resource assert(sound_signature[0] == 'R'); assert(sound_signature[1] == 'I'); assert(sound_signature[2] == 'F'); assert(sound_signature[3] == 'F'); assert(sizeof(sound_signature) == 4); return 0; }EXAMPLE A potential constraint violation from a resource that may not have enough information in an environment that has a
CHAR_BIT
greater than 24.int main (int, char*[]) { const unsigned char arr[] = { #embed "24_bits.bin" limit(1) // may be a constraint violation }; return 0; }Constraints
It may appear zero times or one time in the embed parameter list. Its attribute argument clause shall be present and have the form:
( pp-balanced-token-sequenceopt )
Semantics
The embed parameter with an attribute token
prefix
denotes a balanced preprocessing token sequence within its attribute argument clause that will be placed immediately before the result of the associated#embed
directiveâs expansion, if any.If the resource is empty, then
prefix
has no effect and is ignored.EXAMPLE A null-terminated character array with a prefix value and suffix set of additional tokens when the resource is not empty.
#include <string.h> #include <assert.h> #ifndef SHADER_TARGET #define SHADER_TARGET "ches.glsl" #endif extern char* merp; void init_data () { const char whl[] = { #embed SHADER_TARGET \ prefix(0xEF, 0xBB, 0xBF, ) /* UTF-8 BOM */ \ suffix(,) 0 }; // always null terminated, // contains BOM if not-empty int is_good = (sizeof(whl) == 1 && whl[0] == '\0') || (whl[0] == '\xEF' && whl[1] == '\xBB' && whl[2] == '\xBF' && whl[sizeof(whl) - 1] == '\0'); assert(is_good); strcpy(merp, whl); }Constraints
It may appear zero times or one time in the embed parameter list. Its attribute argument clause shall be present and have the form:
( pp-balanced-token-sequenceopt )
Semantics
The embed parameter with an attribute token
suffix
denotes a balanced preprocessing token sequence within its attribute argument clause that will be placed immediately after the result of the associated#embed
directiveâs expansion.If the resource is empty, then
suffix
has no effect and is ignored.EXAMPLE Extra elements added to array initializer.
#include <string.h> #ifndef SHADER_TARGET #define SHADER_TARGET "edith-impl.glsl" #endif extern char* null_term_shader_data; void fill_in_data () { const char internal_data[] = { #embed SHADER_TARGET \ suffix(,) 0 }; strcpy(null_term_shader_data, internal_data); }
__has_embed
expressions to return 2
alongside the above changes in paragraph 6
7.7. OPTIONAL Add 1 new sub-clause as §6.10.â¨.4, under §6.10.⨠Binary resource inclusion and add an additional modification to the above changes' paragraph 14â¦
The resource (6.10.â¨) identified by the header-name preprocessing token sequence in each contained has_embed expression is searched for as if those preprocessing token were the pp-tokens in a
#embed
directive, except that no further macro expansion is performed. Such a directive shall satisfy the syntactic requirements of a
#embed
directive. The has_embed expression evaluates to:
â 0 if the search fails or if any of the embed parameters in the embed parameter list specified are not supported by the implementation for the
#embed
directive; or,â 1 if the search for the resource succeeds and all embed parameters in the embed parameter list specified are supported by the implementation for the
#embed
directive and the resource is not empty; or,- â 2 if the search for the resource succeeds and all embed parameters in the embed parameter list specified are supported by the implementation for the
#embed
directive and the resource is empty.â¦
EXAMPLE This resource is considered empty due to the
limit ( 0 )
embed parameter, always, including in__has_embed
clauses.int main () { #if __has_embed(</owo/uwurandom> limit(0) prefix(1)) == 2 // if </owo/uwurandom> exits, this // token sequence is always taken. return 0; #else // the resource does not exist #error "The resource does not exist" #endif }
This portion of the proposal must be approved with a separate vote. This does not happen if the previous vote to accept does not exist.
An embed parameter with an attribute token that is one of the following is a standard embed parameter:
limit
â â â âprefix
â â â âsuffix
â â â âis_empty
8. AcknowledgementsConstraints
It may appear zero times or one time in the embed parameter list. Its attribute argument clause shall be present and have the form:
( pp-balanced-token-sequenceopt )
Semantics
The embed parameter with an attribute token
is_empty
denotes a balanced preprocessing token sequence within its attribute argument clause that will replace the#embed
directive entirely.If the resource is not empty, then
is_empty
has no effect and is ignored.EXAMPLE This resource is considered empty due to the
limit ( 0 )
embed parameter, always. This program always returns 0, even if the resource is searched for and found successfully by the implementation.int main () { return #embed </owo/uwurandom> limit(0) prefix(1) is_empty(0) ; // becomes: // return 0; }EXAMPLE An example similar to using the
suffix
embed parameter, but changed slightly.#include <string.h> #ifndef SHADER_TARGET #define SHADER_TARGET "edith-impl.glsl" #endif extern char* null_term_shader_data; void fill_in_data () { const char internal_data[] = { #embed SHADER_TARGET \ suffix(, 0) \ is_empty(0) }; strcpy(null_term_shader_data, internal_data); }
Thank you to Alex Gilding for bolstering this proposal with additional ideas and motivation. Thank you to Aaron Ballman, David Keaton, and Rajan Bhakta for early feedback on this proposal. Thank you to the #include <C++>
for bouncing lots of ideas off the idea in their Discord. Thank you to Hubert Tong for refining the proposalâs implementation-defined extension points.
Thank you to the Lounge<C++> for their continued support, and to rmf for the valuable early implementation feedback.
9. Appendix 9.1. Existing ToolsThis section categorizes some of the platform-specific techniques used to work with C++ and some of the challenges they face. Other techniques used include pre-processing data, link-time based tooling, and assembly-time runtime loading. They are detailed below, for a complete picture of todayâs landscape of options. They include both C and C++ options.
9.1.1. Pre-Processing ToolsRun the tool over the data ( xxd - i xxd_data . bin > xxd_data . h
) to obtain the generated file ( xxd_data . h
) and add a null terminator if necessary:
unsigned char xxd_data_bin[] = { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x0a, 0x00 }; unsigned int xxd_data_bin_len = 13;
Compile main . c
:
#include <stdlib.h> #include <stdio.h> // prefix as const, // even if it generates some warnings in g++/clang++ const #include "xxd_data.h" int main() { const char* data = reinterpret_cast<const char*>(xxd_data_bin); puts(data); // Hello, World! return 0; }
Others still use python or other small scripting languages as part of their build process, outputting data in the exact C++ format that they require.
There are problems with the xxd - i
or similar tool-based approach. Tokenization and Parsing data-as-source-code adds an enormous overhead to actually reading and making that data available.
Binary data as C(++) arrays provide the overhead of having to comma-delimit every single byte present, it also requires that the compiler verify every entry in that array is a valid literal or entry according to the C++ language.
This scales poorly with larger files, and build times suffer for any non-trivial binary file, especially when it scales into Megabytes in size (e.g., firmware and similar).
9.1.2. python
Other companies are forced to create their own ad-hoc tools to embed data and files into their C++ code. MongoDB uses a custom python script, just to format their data for compiler consumption:
import os import sys def jsToHeader(target, source): outFile = target h = [ '#include "mongo/base/string_data.h"', '#include "mongo/scripting/engine.h"', 'namespace mongo {', 'namespace JSFiles{', ] def lineToChars(s): return ','.join(str(ord(c)) for c in (s.rstrip() + '\n')) + ',' for s in source: filename = str(s) objname = os.path.split(filename)[1].split('.')[0] stringname = '_jscode_raw_' + objname h.append('constexpr char ' + stringname + "[] = {") with open(filename, 'r') as f: for line in f: h.append(lineToChars(line)) h.append("0};") # symbols arenât exported w/o this h.append('extern const JSFile %s;' % objname) h.append('const JSFile %s = { "%s", StringData(%s, sizeof(%s) - 1) };' % (objname, filename.replace('\\', '/'), stringname, stringname)) h.append("} // namespace JSFiles") h.append("} // namespace mongo") h.append("") text = '\n'.join(h) with open(outFile, 'wb') as out: try: out.write(text) finally: out.close() if __name__ == "__main__": if len(sys.argv) < 3: print "Must specify [target] [source] " sys.exit(1) jsToHeader(sys.argv[1], sys.argv[2:])
MongoDB were brave enough to share their code with me and make public the things they have to do: other companies have shared many similar concerns, but do not have the same bravery. We thank MongoDB for sharing.
9.1.3. ld
A complete example (does not compile on Visual C++):
Have a file ld_data.bin with the contents Hello , World !
.
Run ld - r binary - o ld_data . o ld_data . bin
.
Compile the following main . cpp
with gcc - std = c ++ 17 ld_data . o main . cpp
:
#include <stdlib.h> #include <stdio.h> #define STRINGIZE_(x) #x #define STRINGIZE(x) STRINGIZE_(x) #ifdef __APPLE__ #include <mach-o/getsect.h> #define DECLARE_LD_(LNAME) extern const unsigned char _section$__DATA__##LNAME[]; #define LD_NAME_(LNAME) _section$__DATA__##LNAME #define LD_SIZE_(LNAME) (getsectbyLNAME("__DATA", "__" STRINGIZE(LNAME))->size) #define DECLARE_LD(LNAME) DECLARE_LD_(LNAME) #define LD_NAME(LNAME) LD_NAME_(LNAME) #define LD_SIZE(LNAME) LD_SIZE_(LNAME) #elif (defined __MINGW32__) /* mingw */ #define DECLARE_LD(LNAME) \ extern const unsigned char binary_##LNAME##_start[]; \ extern const unsigned char binary_##LNAME##_end[]; #define LD_NAME(LNAME) binary_##LNAME##_start #define LD_SIZE(LNAME) ((binary_##LNAME##_end) - (binary_##LNAME##_start)) #define DECLARE_LD(LNAME) DECLARE_LD_(LNAME) #define LD_NAME(LNAME) LD_NAME_(LNAME) #define LD_SIZE(LNAME) LD_SIZE_(LNAME) #else /* gnu/linux ld */ #define DECLARE_LD_(LNAME) \ extern const unsigned char _binary_##LNAME##_start[]; \ extern const unsigned char _binary_##LNAME##_end[]; #define LD_NAME_(LNAME) _binary_##LNAME##_start #define LD_SIZE_(LNAME) ((_binary_##LNAME##_end) - (_binary_##LNAME##_start)) #define DECLARE_LD(LNAME) DECLARE_LD_(LNAME) #define LD_NAME(LNAME) LD_NAME_(LNAME) #define LD_SIZE(LNAME) LD_SIZE_(LNAME) #endif DECLARE_LD(ld_data_bin); int main() { const char* p_data = reinterpret_cast<const char*>(LD_NAME(ld_data_bin)); // impossible, not null-terminated //puts(p_data); // must copy instead return 0; }
This scales a little bit better in terms of raw compilation time but is shockingly OS, vendor and platform specific in ways that novice developers would not be able to handle fully. The macros are required to erase differences, lest subtle differences in name will destroy oneâs ability to use these macros effectively. We omitted the code for handling VC++ resource files because it is excessively verbose than what is present here.
N.B.: Because these declarations are extern
, the values in the array cannot be accessed at compilation/translation-time.
incbin
There is a tool called incbin
which is a 3rd party attempt at pulling files in at "assembly time". Its approach is incredibly similar to ld
, with the caveat that files must be shipped with their binary. It unfortunately falls prey to the same problems of cross-platform woes when dealing with Visual C, requiring additional pre-processing to work out in full.
xxd
, but done Raw
Some people cannot even use the xxd
tool on their platforms because it cannot be used. This is the case where tools need to be able to package things, and therefore their build tools need to accommodate for not having their information. The way to help save for this is to create other small utilities that effectively duplicate the tools, but in different ways.
This has affected packaging of Debian-style packages on multiple distributions.
9.2. Type FlexibilityNote: As per the vote in the September C++ Evolution Working Group Meeting, Type Flexibility is not being pursued in the preprocessor for various implementation and support splitting concerns.
A type can be specified after the #embed
to view the data in a very specific manner. This allows data to initialized as exactly that type.
Type flexibility was not pursued for various implementation concerns. Chief among them was single-purpose preprocessors that did not have access to frontend information. This meant it was very hard to make a system that was both preprocessor conformant but did not require e.g. sizeof (...)
information at the point of preprocessor invocation. Therefore, the type flexibility feature was pulled from #embed
and will be conglomerated in other additions such as std :: bitcast
or std :: embed
.
/* specify a type-name to change array type */ const int shorten_flac[] = { #embed int "stripped_music.flac" };
The contents of the resource are mapped in an implementation-defined manner to the data, such that it will use sizeof ( type - name ) * CHAR_BIT
bits for each element. If the file does not have enough bits to fill out a multiple of sizeof ( type - name ) * CHAR_BIT
bits, then a diagnostic is required. Furthermore, we require that the type passed to #embed
that must one of the following fundamental types, signed or unsigned, spelled exactly in this manner:
char
, unsigned char
, signed char
short
, unsigned short
, signed short
int
, unsigned int
, signed int
long
, unsigned long
, signed long
long long
, unsigned long long
, signed long long
More types can be supported by the implementation if the implementation so chooses (both the GCC and Clang prototypes described below support more than this). The reason exactly these types are required is because these are the only types for which there is a suitable way to obtain their size at pre-processor time. Quoting from §5.2.4.2.1, paragraph 1:
The values given below shall be replaced by constant expressions suitable for use in
#if
preprocessing directives.
This means that the types above have a specific size that can be properly initialized by a preprocessor entirely independent of a proper C frontend, without needing to know more than how to be a preprocessor. Originally, the proposal required that every use of #embed
is accompanied by a #include <limits.h>
(or, in the case of C++, #include <climits>
). Instead, the proposal now lets the implementation "figure it out" on an implementation-by-implementation basis.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4