Is there a way to load a binary file as a const variable in C at compile time

我怕爱的太早我们不能终老 提交于 2019-11-30 13:39:39

No you can't do this directly. One way is to convert your binary files into C source code and include these pieces into your project. The conversion can be done by a simple program written by you or by some third party program.

For example:

Binaray1.c (generated automatically)

unsigned char binaray_file1[] =
{
  1,2,3,10,20,
  ....
} ;

Binaray2.c (generated automatically)

unsigned char binaray_file2[] =
{
  0,0,10,20,45,32,212,
  ....
} ;

SomeSourceFile.c

extern unsigned char binary_file1[] ;
extern unsigned char binary_file2[] ;

// use binary_file1 and binary_file2 here.
John Zwinck

The usual way to do this on Unix-like systems is using ld -r binary. Here's a tutorial for Linux: http://www.burtonini.com/blog/computers/ld-blobs-2007-07-13-15-50

And one for Mac OS X, which is a little more complex: Compile a binary file for linking OSX

The idea is to have the linker create an object file with known symbol names which point to the beginning and end of a binary blob which it copies into the resulting object file. You then link that object file into your application, and reference the blob via extern char* pointers or so.

I suppose you know how to link objects on your system, so the remaining question is whether your linker supports something like -r binary.

Of course you could invent your own format, but before you do so: have a look into the XPM bitmap format which is exactly meant for that purpose: integrating pixmaps into C source code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!