The Pragmatic Addict

Store static binary data in your C program

There are many ways to skin this cat. Of all of them xxd is my favorite because it is the easiest to port to various platforms.

xxd

This little utility comes from the same makers as vim. It can be found in most, if not all linux distros. This program will convert a source file into a hex dump, even better it will format it to be C compatible.

I use the output to write into a .h file for inclusion into my programs. No object linking involved! One downside is that your compile memory requirements could exceed your system memory if you have a REALLY HUGE file.

xxd -include helloworld.txt
unsigned char helloworld_txt[] = {
  0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21,
  0x0a
};
unsigned int helloworld_txt_len = 13;

ld

This was what I used early on. Basically you just convert the binary file into an object file for linking to your program. It works amazingly well and doesn’t have the memory restrictions like xxd. The object file will have pointers to the data rather than formally defined char[] types etc.

The downside is portability, I did get this to work with mingw but porting to an apple environment caused problems.

ld --relocatable --format=binary helloworld.txt --output=helloworld.o

To retrieve the generated variable pointer names:

objdump --syms helloworld.o
helloworld.o:     file format elf64-x86-64

SYMBOL TABLE:
0000000000000000 l    d  .data  0000000000000000 .data
000000000000000d g       .data  0000000000000000 _binary_helloworld_txt_end
0000000000000000 g       .data  0000000000000000 _binary_helloworld_txt_start
000000000000000d g       *ABS*  0000000000000000 _binary_helloworld_txt_size

Created: 2024-04-12 Modified: 2024-04-11