我可以将普通文件链接到我的可执行文件中吗?

Can I link a plain file into my executable?

本文关键字:可执行文件 我的 链接 文件 我可以      更新时间:2023-10-16

某些框架(Qt,Windows,Gtk...)提供了向二进制文件添加资源的功能。 我想知道是否有可能在没有框架的情况下实现这一目标,因为真正需要

的是
  1. 在二进制文件(数据段)中包含资源地址的符号
  2. 表示资源长度的符号
  3. 资源本身

如何使用 gcc 工具链实现这一点?

你可以

这样做:

objcopy --input binary 
        --output elf32-i386 
        --binary-architecture i386 my_file.xml myfile.o

这将生成一个对象文件,您可以将其链接到可执行文件中。此文件将包含这些符号,您必须在 C 代码中声明这些符号能够使用它们

00000550 D _binary_my_file_xml_end
00000550 A _binary_my_file_xml_size 
00000000 D _binary_my_file_xml_start

最基本的等价物是一个充满字节的char数组。

在 Linux 上,您可以使用 xxd -i <file> 将文件"编译"为char数组,然后将数组链接到二进制文件中,并随心所欲地使用组成字节。

这是我自己的代码makefile的一个例子,它创建了一个名为templates.h的"资源文件",其中包含一堆表示HTML模板的char数组:

templates.h:
    @echo "#ifndef REDACTED_TEMPLATES_H" > templates.h
    @echo "#define REDACTED_TEMPLATES_H" >> templates.h
    @echo "// Auto-generated file! Do not modify!" >> templates.h
    @echo "// NB: arrays are not null-terminated" >> templates.h
    @echo "// (anonymous namespace used to force internal linkage)" >> templates.h
    @echo "namespace {" >> templates.h
    @echo "namespace templates {" >> templates.h
    @cd templates;
    for i in * ;
    do 
        echo "Compiling $$i...";
        xxd -i $$i | sed -e 's/ =/ __attribute__((unused)) =/' >> ../templates.h;
    done;
    cd ..
    @echo "}" >> templates.h
    @echo "}" >> templates.h
    @echo "#endif" >> templates.h

另请参阅:如何以编程方式最好地将"__attribute__(未使用))"应用于这些自动生成的对象?

结果看起来有点像:

#ifndef REDACTED_TEMPLATES_H
#define REDACTED_TEMPLATES_H
// Auto-generated file! Do not modify!
// NB: arrays are not null-terminated
// (anonymous namespace used to force internal linkage)
namespace {
namespace templates {
unsigned char alert_email_finished_events_html[] __attribute__((unused)) = {
  0x3c, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73,
  0x3d, 0x22, 0x6e, 0x6f, 0x64, 0x65, 0x2d, 0x69, 0x6e, 0x66, 0x6f, 0x2d,
[..]
  0x7d, 0x7d, 0x0d, 0x0a, 0x3c, 0x2f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x3e,
  0x0d, 0x0a
};
unsigned int alert_email_finished_events_html_len __attribute__((unused)) = 290;
unsigned char alert_email_finished_events_list_html[] __attribute__((unused)) = {
  0x3c, 0x74, 0x72, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x73,
  0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x2d, 0x70, 0x72, 0x65, 0x76,
[..]
  0x73, 0x74, 0x7d, 0x7d, 0x0d, 0x0a
};
unsigned int alert_email_finished_events_list_html_len __attribute__((unused)) = 42;
}
}
#endif

请注意,当仅在一个翻译单元中使用资源时,此特定示例是最佳选择,但可以调整常规方法以满足您的需求。