diff options
| -rw-r--r-- | content/notes/2024-06-19-embedding-resources-into-binary-with-c.md | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/content/notes/2024-06-19-embedding-resources-into-binary-with-c.md b/content/notes/2024-06-19-embedding-resources-into-binary-with-c.md new file mode 100644 index 0000000..f552f01 --- /dev/null +++ b/content/notes/2024-06-19-embedding-resources-into-binary-with-c.md | |||
| @@ -0,0 +1,57 @@ | |||
| 1 | --- | ||
| 2 | title: "Embedding resources into binary with C" | ||
| 3 | url: embedding-resources-into-binary-with-c.html | ||
| 4 | date: 2024-06-19T16:13:13+02:00 | ||
| 5 | type: note | ||
| 6 | draft: false | ||
| 7 | tags: [c] | ||
| 8 | --- | ||
| 9 | |||
| 10 | [Binary resource inclusion](https://en.cppreference.com/w/c/preprocessor/embed) | ||
| 11 | preprocessor has been put into the C23 standard but has not yet been | ||
| 12 | implemented by the compilers. | ||
| 13 | |||
| 14 | Until then a workaround with | ||
| 15 | [`xxd`](https://en.cppreference.com/w/c/preprocessor/embed) is possible without | ||
| 16 | spending time on rolling out your own. | ||
| 17 | |||
| 18 | `xxd` has an option to export to C header file which makes this much easier. | ||
| 19 | This works for all files be that text files or binary ones such as images, etc. | ||
| 20 | |||
| 21 | Convert `text.txt` into a C header file with `xxd -i test.txt > test.h`. This | ||
| 22 | creates the following file and uses the filename for variable names. | ||
| 23 | |||
| 24 | ```c | ||
| 25 | // test.h | ||
| 26 | unsigned char test_txt[] = { | ||
| 27 | 0x54, 0x68, 0x65, 0x20, 0x66, 0x69, 0x72, 0x73, 0x74, 0x20, 0x72, 0x75, | ||
| 28 | 0x6c, 0x65, 0x20, 0x69, 0x73, 0x20, 0x74, 0x79, 0x70, 0x69, 0x63, 0x61, | ||
| 29 | 0x6c, 0x20, 0x6f, 0x66, 0x20, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x75, 0x6d, | ||
| 30 | ... | ||
| 31 | }; | ||
| 32 | unsigned int test_txt_len = 547; | ||
| 33 | ``` | ||
| 34 | |||
| 35 | Then use it in C in this manner. | ||
| 36 | |||
| 37 | ```c | ||
| 38 | // main.c | ||
| 39 | #include <stdio.h> | ||
| 40 | #include "test.h" | ||
| 41 | |||
| 42 | int main(void) { | ||
| 43 | printf("Testing embedding of files into binary.\n"); | ||
| 44 | |||
| 45 | for (unsigned int i = 0; i < test_txt_len; i++) { | ||
| 46 | printf("%02x ", test_txt[i]); | ||
| 47 | } | ||
| 48 | printf("\n\n"); | ||
| 49 | |||
| 50 | for (unsigned int i = 0; i < test_txt_len; i++) { | ||
| 51 | printf("%c", test_txt[i]); | ||
| 52 | } | ||
| 53 | printf("\n\n"); | ||
| 54 | |||
| 55 | return 0; | ||
| 56 | } | ||
| 57 | ``` | ||
