A handy trick for embedding a file in a C or C++ binary as a byte array.
You can embed a file in a C or C++ binary as a byte array using the standard Unix utility xxd
.
$ echo "test data" > data_file $ xxd -i data_file
This prints the following to standard output:
unsigned char data_file[] = { 0x74, 0x65, 0x73, 0x74, 0x20, 0x64, 0x61, 0x74, 0x61, 0x0a }; unsigned int data_file_len = 10;
You can write the output to a .c
or .h
file and include it directly in your source using an #include
statement:
$ xxd -i data_file > data_file.c
If you want to access the variables from another file without including the source file directly, you'll need to use extern
declarations:
extern unsigned char data_file[]; extern unsigned int data_file_len;
Note that the array produced by xxd
isn't null-terminated so you can't use it directly as a C string.
Here's an alternative technique that works for embedding strings:
$ xxd -i < data_file > data_file.xxd $ echo ', 0x00' >> data_file.xxd
Note that we're piping the input file into xxd
this time instead of supplying its file name as an argument.
This creates a hex-encoded byte dump without the C array wrapper. You can include it directly into a source file like this:
char data[] = { #include "data_file.xxd" };