2024 年 6 月 19 日,在Mitja Felicijan 的博客上提到:
- 二进制资源包含预处理器已被纳入 C23 标准,但尚未被编译器实现。
- 在那之前,无需花费时间推出自己的方法,可使用
xxd
进行变通。 xxd
有一个导出为 C 头文件的选项,这使得操作更简单,此方法适用于所有文件,包括文本文件和二进制文件(如图像等)。- 示例:将
text.txt
转换为 C 头文件,使用xxd -i test.txt > test.h
,会创建如下文件,使用文件名作为变量名。
// test.h unsigned char test_txt[] = { 0x54, 0x68, 0x65, 0x20, 0x66, 0x69, 0x72, 0x73, 0x74, 0x20, 0x72, 0x75, 0x6c, 0x65, 0x20, 0x69, 0x73, 0x20, 0x74, 0x79, 0x70, 0x69, 0x63, 0x61, 0x6c, 0x20, 0x6f, 0x66, 0x20, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x75, 0x6d, ... }; unsigned int test_txt_len = 547;
- 在 C 中使用方式如下:
// main.c #include <stdio.h> #include "test.h" int main(void) { printf("Testing embedding of files into binary.\n"); for (unsigned int i = 0; i < test_txt_len; i++) { printf("%02x ", test_txt[i]); } printf("\n\n"); for (unsigned int i = 0; i < test_txt_len; i++) { printf("%c", test_txt[i]); } printf("\n\n"); return 0; }
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。