theanine
theanine

Reputation: 1008

How do you embed resource files in C?

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?

Upvotes: 5

Views: 5851

Answers (3)

Jahn
Jahn

Reputation: 113

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.

Upvotes: 0

blueshift
blueshift

Reputation: 6881

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.

Upvotes: 3

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215517

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.

Upvotes: 2

Related Questions