Embedding resources into binary with C

note, Jun 19, 2024, on Mitja Felicijan's blog

Binary resource inclusion preprocessor has been put into the C23 standard but has not yet been implemented by the compilers.

Until then a workaround with xxd is possible without spending time on rolling out your own.

xxd has an option to export to C header file which makes this much easier. This works for all files be that text files or binary ones such as images, etc.

Convert text.txt into a C header file with xxd -i test.txt > test.h. This creates the following file and uses the filename for variable names.

// test.h
unsigned char test_txt[] = {
  0x54, 0x68, 0x65, 0x20, 0x66, 0x69, 0x72, 0x73, 0x74, 0x20, 0x72, 0x75,
  0x6c, 0x65, 0x20, 0x69, 0x73, 0x20, 0x74, 0x79, 0x70, 0x69, 0x63, 0x61,
  0x6c, 0x20, 0x6f, 0x66, 0x20, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x75, 0x6d,
  ...
  };
unsigned int test_txt_len = 547;

Then use it in C in this manner.

// main.c
#include <stdio.h>
#include "test.h"

int main(void) {
  printf("Testing embedding of files into binary.\n");

  for (unsigned int i = 0; i < test_txt_len; i++) {
    printf("%02x ", test_txt[i]);
  }
  printf("\n\n");

  for (unsigned int i = 0; i < test_txt_len; i++) {
    printf("%c", test_txt[i]);
  }
  printf("\n\n");

  return 0;
}

Other notes

DateTitle
Aerial photography of algae spotted on river Sava
10/GUI 10 Finger Multitouch User Interface
Sane defaults for tmux with more visible statusbar
Run 9front in Qemuplan9
Display xterm color palette
Add lazy loading of images in Jekyll posts
Make B/W SVG charts with matplotlib
Lua performance in different environments
Sane default for Dungeon Crawl Stone Soup Online editiondcss
Extend Lua with custom C functions using Clangc
My brand new Plan9/9front desktopplan9
Cache busting in Hugo
Previews how man page written in Troff will look like
60's IBM Computers Commercial
Personal sane Vim defaultsvim