How do you embed resource files in C?

2019-04-30 12:42发布

问题:

The only way I know how to do this is to convert the file into a C source file with a single byte/char array containing the contents of the resource file in hex.

Is there a better or easier way to do this?

回答1:

Here's a nice trick I use with a gcc-arm cross compiler; including a file through an assembly language file. In this example it's the contents of the file public_key.pem I'm including.

pubkey.s

 .section ".rodata"
 .globl pubkey
 .type pubkey, STT_OBJECT
pubkey:
 .incbin "public_key.pem"
 .byte 0
 .size pubkey, .-pubkey

corresponding pubkey.h

#ifndef PUBKEY_H
#define PUBKEY_H
/*
 * This is a binary blob, the public key in PEM format,
 * brought in by pubkey.s
 */
extern const char pubkey[];

#endif // PUBKEY_H

Now the C sources can include pubkey.h, compile the pubkey.s with gcc and link it into your application, and there you go. sizeof(pubkey) also works.



回答2:

The way you've described is the best/easiest/most portable. Just write a quick tool (or find an existing one) to generate the C files for you. And make sure you make correct use of the const (and possibly static) keywords when you do it or your program will waste large amounts of memory.



回答3:

I needed something like this a while ago and I created a tool for this. It's a python tool called mkcres (https://github.com/jahnf/mkcres) and I put it on github.

  • Although documentation is lacking a little, there are examples on how to integrate it into a build process with CMake or plain make files.
  • Takes a .json file as resource file generation configuration
  • It can detect changes on resource files and automatically regenerate the corresponding C files if necessary.
  • Downside: You'll need python (2 or 3)
  • Upside: Not compiler specific, should work with every C/C++ compiler.