简单且独立于工具链的方法是从二进制数据生成一个 C 代码(或程序集)数组,然后以正常方式编译并链接到您的代码。
编写自己的工具来做这件事是微不足道的,但已经有工具可以为你做这件事。例如,SRecord 工具套件包含此功能:
srec_cat mybinary.bin -binary -o mybinary.c -C-Array mybinary -INClude
将生成两个包含格式代码的文件(省略的示例 - 您的输出会有所不同):
mybinary.c
/* http://srecord.sourceforge.net/ */
const unsigned char mybinary[] =
{
0xC0, 0x91, 0x00, 0x20, 0xA5, 0x01, 0x00, 0x08, 0xB1, 0x11, 0x00, 0x08,
...
0x31, 0x31, 0x30, 0x31, 0x30, 0x30, 0x2E, 0x30, 0x31, 0x2E, 0x30, 0x35,
0x2E, 0x30, 0x30, 0x00,
};
const unsigned long mybinary_termination = 0x00000185;
const unsigned long mybinary_start = 0x00000000;
const unsigned long mybinary_finish = 0x00004000;
const unsigned long mybinary_length = 0x00004000;
#define MYBINARY_TERMINATION 0x00000185
#define MYBINARY_START 0x00000000
#define MYBINARY_FINISH 0x00004000
#define MYBINARY_LENGTH 0x00004000
mybinary.h
#ifndef SRC_MYBINARY_H
#define SRC_MYBINARY_H
extern const unsigned long mybinary_termination;
extern const unsigned long mybinary_start;
extern const unsigned long mybinary_finish;
extern const unsigned long mybinary_length;
extern const unsigned char mybinary[];
#endif /* SRC_MYBINARY_H*/
SRecord 工具复杂而神秘,但非常强大,可用于各种二进制文件和目标文件的转换和操作。如果您更喜欢只做这一项工作的更简单的东西,那么 "binary to C code" 是一个合适的搜索词。我过去专门用过的例子:
它们都生成与上述大致相似的代码。
如果您需要在特定位置定位二进制文件,则需要使用工具链特定方法修改生成的代码。以 IAR 为例:
#pragma location=0x8020000
const unsigned char mybinary[] =
{...} ;
或
const unsigned char mybinary[] @ 0x8020000 =
{...} ;
同样,您可以在用户定义的链接器部分中定位数据 - 允许链接器确定位置:
const unsigned char mybinary[] @ "BIN_SECTION" =
{...} ;
跨工具链的语法不同。我还没有尝试过,但是 SRecord -C-Array 过滤器具有 −POSTfix string 和 −PREfix string 修饰符,可用于在生成中添加特定于工具链的扩展(如果经常修改二进制文件,这很方便)。但是 IAR 语法没有很好的定义,所有的例子都是这样的:
<type> <symbol> @<location> = <initialiser> ;
所以“中缀”不是前缀或后缀。可能是这样的:
<type> <symbol> = <initialiser> @<location> ;
是有效的,但据我所知,手册并没有正式指定语法,而且我没有工具可以测试。如果这确实有效,那么:
srec_cat mybinary.bin -binary -o mybinary.c -C-Array mybinary -INClude -POSTfix "@ 0x8020000"
const unsigned char mybinary[] =
{...} @ 0x8020000 ;
对于链接器部分的位置:
-POSTfix `@ "BIN_SECTION"`
如果此语法不起作用,您可以编写自己的工具来修改生成的代码并作为自定义构建步骤运行以实现自动化,或者使用文本处理工具(例如 sed)插入位置信息。例如:
sed 's/mybinary\[\] =/mybinary\[\] @ 0x8020000 =/' mybinary.c
在 mybinary.c 中用 char mybinary[] @ 0x8020000 = 替换 char mybinary[] =
一般情况下,除非数据要被一些独立链接的代码代码访问,或者独立于代码进行修补/更新,否则没有必要将数据定位在特定位置,您应该让链接器定位它以实现可移植性在工具链和运行时环境之间。