Generate C-Compatible Byte Array from File using CMake

Generate C-Compatible Byte Array from File using CMake

In embedded systems, firmware development, or scenarios where static assets must be compiled directly into a binary, converting file contents into a C-compatible byte array is a common requirement. This technique allows resources such as text files, images, or other binary data to be embedded into the program without relying on a filesystem at runtime. CMake provides a built-in solution for this task without requiring external tools, such as xxd. This tutorial explains how to generate C-compatible byte array from file using CMake.

Create a simple file test.txt without a trailing newline:

test.txt

Hello world

CMake provides a built-in bin2c command which supports custom formatting through a template file. This makes it possible to control how the generated array and length variables are structured. Create the template file:

bin2c_template.txt

unsigned char test_txt[] = {@array@};
unsigned int test_txt_len = @length@;

Generate the C byte array using the following command:

cmake -E bin2c --template-file bin2c_template.txt test.txt

The command will print the result directly to the terminal:

unsigned char test_txt[] = {
  0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 0x6F, 0x72, 0x6C, 0x64
};
unsigned int test_txt_len = 11;

To store the generated array in a header file for later inclusion, run the command:

cmake -E bin2c --template-file bin2c_template.txt test.txt test.h

The file test.h will contain the formatted byte array and its size.

Leave a Comment

Cancel reply

Your email address will not be published.