aboutsummaryrefslogtreecommitdiff
path: root/content
diff options
context:
space:
mode:
authorMitja Felicijan <mitja.felicijan@gmail.com>2024-06-19 19:16:50 +0200
committerMitja Felicijan <mitja.felicijan@gmail.com>2024-06-19 19:16:50 +0200
commit38379cbbbe7ff3ad391b9bbc47a2ad3a638d6210 (patch)
tree076ea07ac0e1cbd94cda91aab501f9dfa9bcbd30 /content
parent90b1964f05f44beefaee01ff7bf9023d4742faad (diff)
downloadmitjafelicijan.com-38379cbbbe7ff3ad391b9bbc47a2ad3a638d6210.tar.gz
Notes: Embedding resources into binary with C
Diffstat (limited to 'content')
-rw-r--r--content/notes/2024-06-19-embedding-resources-into-binary-with-c.md57
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---
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
15[`xxd`](https://en.cppreference.com/w/c/preprocessor/embed) is possible without
16spending time on rolling out your own.
17
18`xxd` has an option to export to C header file which makes this much easier.
19This works for all files be that text files or binary ones such as images, etc.
20
21Convert `text.txt` into a C header file with `xxd -i test.txt > test.h`. This
22creates the following file and uses the filename for variable names.
23
24```c
25// test.h
26unsigned 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 };
32unsigned int test_txt_len = 547;
33```
34
35Then use it in C in this manner.
36
37```c
38// main.c
39#include <stdio.h>
40#include "test.h"
41
42int 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```