Use xxd to create C headers
xxd is a classic hexdump tool available on most Linux distros that I've encountered. Mostly people use it to inspect hexdumps from binaries, but it has a surprising amount of functionality above and beyond that: it can revert hexdumps to binary, it can patch hexdump output back into an existing binary file, and (the subject of this note) it can format its output as a C header file.
xxd -i ${file}
, where -i
stands for include, will output the contents of the input file as an array of unsigned char
followed by the length of the array as an unsigned int
. I've been using this lately as a quick way to include arbitrary binary data into compiled objects which I then flash onto a microcontroller or another limited system (like with my font for the GameBoy). This makes the binary really easy to address and use in the rest of my code. The downside is that this blows up the header files and can slow down compilation; this hasn't been a problem for me so far since all the projects have been prototypes or PoCs. If I were to need to do this for more mature projects, I would probably use a linker script but the longer I can put off writing linker scripts in a project, the happier I am.
As a side-note: I did a brief search for any kind of history of the xxd utility. It seems to come packaged with Vim, and the creator Tony Nugent is quoted in the cute quotes part of the Vim docs, but I've also seen indications that it existed in a form before it was packaged with Vim. Email me if you have any sources or know more!