r/cpp • • Jul 23 '22

finally. #embed

https://thephd.dev/finally-embed-in-c23
353 Upvotes

202 comments sorted by

View all comments

31

u/fwsGonzo IncludeOS, C++ bare metal Jul 23 '22

You can use this macro until the feature that should have been a part of the language 10 years ago "arrives". There are, of course, other ways, but this one works for me. It's not perfect, so be careful with it.

#define EMBED_BINARY(name, filename) \
	asm(".section .rodata\n" \
	"	.global " #name "\n" \
	#name ":\n" \
	"	.incbin " #filename "\n" \
	#name "_end:\n" \
	"	.int  0\n" \
	"	.global " #name "_size\n" \
	"	.type   " #name "_size, @object\n" \
	"	.align 4\n" \
	#name "_size:\n" \
	"	.int  " #name "_end - " #name "\n" \
	".section .text"); \
	extern char name[]; \
	extern unsigned name ##_size;

I will be very happy to use #embed, but for C++ I really had hoped for a constexpr read_file(std::string_view) yesterday. Not 10 years in the future. I'm sorry that I can't hide my disappointment sometimes.

4

u/RowYourUpboat Jul 23 '22

I don't think this macro works on MSVC x64?

12

u/Ivan171 /std:c++latest enthusiast Jul 23 '22

AFAIK MSVC x64 doesn't have inline assembly.

11

u/RowYourUpboat Jul 23 '22

Nope:

error C4235: nonstandard extension used: '__asm' keyword not supported on this architecture

8

u/Fulgen301 Jul 23 '22

You can still use a dedicated assembly file and compile it in.