Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 344
theanine Avatar asked Apr 05 '12 22:04

theanine


1 Answers

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.

like image 175
blueshift Avatar answered Oct 25 '22 13:10

blueshift