embedding-binary-data-in-executables

原文csl.name/post/embedding-binary-data

方法一

直接将二进制文件转成C语言的数组, 类似: const char data[] = {0x00, 0x01, 0x02, ...};

可直接使用工具转换: xxd -i test.png

方法二

使用GNU Linker:

1
ld -r -b binary test.png -o test.o

生成.o之后, 用nm命令查看内部的符号:

1
2
3
4
nm test.o
... D _binary_test_png_end
... A _binary_test_png_size
... D _binary_test_png_start

可看到上面有3个符号, 直接在.c/.cpp源文件中定义即可

1
2
3
extern const char _binary_test_png_end[];
extern const int _binary_test_png_size; // 不建议使用这个大小
extern const char _binary_test_png_start[];

不建议直接使用_binary_test_png_size, 编译有错误或者直接访问时导致段错误
长度可以直接使用_binary_test_png_end - _binary_test_png_start获取

然后编译时加上上面的test.o

这里有完整的cmake使用例子codes