5 ms·
Just wait till you find out that you can do: const char *s = #include "test.txt" ;
by KMnO4 4y ago
Just wait till you find out that you can do:
const char *s =
#include "test.txt"
;
- unwind 4y agoSure, but only if the text file looks like a C string literal, i.e. starts and ends with double quotes (which would make it into a weird text file). Doing const char *s = " #inclued "test.txt" "; won't work, since the preprocessor won't interpret directives inside string literals of course. In many assemblers, there is a directive called "incbin" which pastes in unstructured binary data at the point of usage. I just found a very clever C and C++ wrapper [1] for that, which gives you an INCBIN() macro. Nice! [1]: https://github.com/graphitemaster/incbin https://github.com/graphitemaster/incbin
- cygx 4y agoNote that C23 will include a variant of incbin spelled #embed: Semantically, the preprocessor will insert a list of integers which you can use to initialize an array.
- jsmith45 4y agoAlso, for clarity, it is fully expected that the compiler will use the as-if rule to optimize it. Most likely by having a dedicated token/ast node that only decomposes to comma separated values if if actually needs to, with common usage in initalizers being handled by simply copying the data directly into a static data segment without ever creating an integer list at all.
- a_e_k 4y agoAn incbin-like facility is coming to the standard: https://thephd.dev/finally-embed-in-c23 https://thephd.dev/finally-embed-in-c23
- unwind 4y agoYeah, I actually had heard about that but it didn't show up in my first search. Thanks!
- iforgotpassword 4y agoYeah, ignoring incbin hackery, a better example than strings might be float vertices[] = { #include "stuff.txt" };