最基本的等价物是一个充满字节的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
(另见:How best can I programmatically apply `__attribute__ ((unused))` to these auto-generated objects?)
结果看起来有点像:
#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
请注意,当仅在一个翻译单元中使用资源时,此特定示例是最佳选择,但可以调整通用方法以满足您的需求。