1. 8
  1.  

  2. 6

    Much simpler solution that often might be enough is xxd -i.

    1. 4

      Author of koio here.

      objcopy is another simpler, good choice. I need koio to provide a stdio-like API and a consistent external baseline for how embedding files is done in chopsui so that it can be consistent between chopsui, third-party chopsui libraries, chopsui applications, and end-user extensibility. To that end I found it more appropriate to write a tool like this.

    2. 3

      Another option for those willing to use GNU C extensions is a small inline assembly fragment with the .incbin directive…wrapped up in a convenient macro approximating the usage in the article (the .len member here is admittedly a bit hackish), perhaps something like:

      #include <stdio.h>
      
      #define DATA_FILE(name, file)  \
      	extern const char _##name##_data[], _##name##_len[]; \
      	asm(".pushsection .rodata\n" \
      	    ".local _" #name "_data\n" \
      	    "_" #name "_data:\n" \
      	    ".incbin \"" file "\"\n" \
      	    ".local _" #name "_len\n" \
      	    ".set _" #name "_len, . - _" #name "_data\n" \
      	    "_" #name "_data_end:\n" \
      	    ".byte 0\n" \
      	    ".popsection"); \
      	static const struct { \
      		const char* path; \
      		const char* data; \
      		size_t len; \
      	} name = { \
      		.path = file, \
      		.data = _##name##_data, \
      		.len = (size_t)&_##name##_len, \
      	}
      
      DATA_FILE(foo, "foo"); /* replace with __FILE__ for a cheater-quine... */
      
      int main(void)
      {
      	fwrite(foo.data, 1, foo.len, stdout);
      	return 0;
      }
      

      (This approach has the disadvantage of introducing an external file dependency that -M flags won’t report, however, so it’ll probably require a manual annotation in your makefile.)

      1. 2

        On illumos systems we have elfwrap(1), which will create an object file with a symbol for the start and end of a region containing the bytes from the wrapped file that you can then link into C or C-like programs.

        1. 1

          FWIW, I also made a tool like this: pyxxd

          1. 1

            More tools like this:

            • objres - any file ‘compiled’ into an object file, with corresponding symbol.
            • bin2s (a, b) - outputs GAS code