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