我可以链接一个纯文件到我的可执行文件吗?

一些框架(Qt,Windows,Gtk等)提供了将资源添加到二进制文件的function。 我想知道如果没有这个框架,是否有可能实现这一点,因为所有真正需要的是

  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>xxd -i <file> “编译”为char数组,然后将这些数组链接到您的二进制文件中,然后使用组成字节。

下面是我自己代码的makefile的一个例子,它创build一个名为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__((unused))`应用于这些自动生成的对象? )

结果看起来有点像:

 #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 

请注意,仅在一个翻译单元中使用资源时,此特定示例是最佳select,但可以调整一般方法以适应您的需要。