Resource inclusion (since C++26)
From cppreference.com
< cpp | preprocessor
#embed is a preprocessor directive to include resources, where a resource is defined as a source of data accessible from the translation environment.
Contents |
[edit] Syntax
#embed < resource > pp-tokens (optional) \n *
|
(1) | ||||||||
#embed " resource " pp-tokens (optional) \n *
|
(2) | ||||||||
#embed pp-tokens\n *
|
(3) | ||||||||
__has_embed ( pp-balanced-token-seq )
|
(4) | ||||||||
1) Searches for a uniquely identified resource.
2) Searches for a named resource. Fallbacks to (1) as if chevrons were used instead of quotes.
1-2) Replaces the directive by a comma separated list of integers corresponding to the data of the resource.
3) If neither (1) nor (2) is matched, pp-tokens will undergo macro replacement. The directive after replacement will be tried to match with (1) or (2) again.
resource | - | A resource to embed | ||
pp-tokens | - | Positive number of preprocessing tokens | ||
pp-balanced-token-seq | - |
|
[edit] Explanation
1) A search takes place in a sequence of implementation-defined places. How the places are specified or the resource identified is implementation-defined.
2) A search takes place in an implementation-defined manner. A fallback follows if this search is not supported, or if the search fails.
[edit] Embed parameters
This section is incomplete Reason: [cpp.embed.param] |
[edit] Example
Assume the file word.txt
contains a single word: worlds.
- limit(5) limits embeding to 5 characters (effectively embeding the word world without the leading leter s).
- prefix(0x2C, 0x20, ) prepends , to the string
s
: 0x2C is a hex code of , and 0x20 is a hex code of . - suffix(, 0x21) appends ! to the string
s
: 0x21 is a hex code of !.
Run this code
#include <string> #include <print> int main() { std::string s { #embed "word.txt" prefix(0x2C, 0x20, ) suffix(, 0x21) limit(5) }; std::println("Hello{}", s); }
Possible output:
Hello, world!
[edit] References
- C++26 standard (ISO/IEC 14882:2026):
- 15.4 Resource inclusion [cpp.embed]
[edit] See also
C documentation for Binary resource inclusion (since C23)
|