使用objcopy实现将文件编译进执行程序
一、简介
工作中可能遇到将一个文件编译进执行程序的需求,例如bin文件、jpg文件等等。实现的方法可以使用脚本来将文件内容写入一个新的C源文件数组,达成编译进程序的目的。
现在介绍一种简单、快捷的方法来实现需求,具体的操作如下文所述。
二、环境准备
<file> 文件内容:
This is a test.
<test.c> 文件内容:
1 #include <stdio.h>
2
3 extern unsigned char _binary_file_start[];
4 extern unsigned char _binary_file_end[];
5
6 int main()
7 {
8 unsigned char *p = _binary_file_start;
9 unsigned char *end = _binary_file_end;
10
11 while(p != end)
12 {
13 printf("%c", *p++);
14 }
15
16 return 0;
17 }
三、操作指令
将文件内容插入 <file.o>:
objcopy -I binary -O elf64-x86-64 -B i386 file file.o
编译源文件:
gcc test.c file.o
四、程序运行
# ./a.out
This is a test.
大功告成,达到了预期的效果。
感谢花费宝贵的时间浏览,
转载请注明出处。
本人将在[资源共享]分类下陆续加入学习过程中一些比较重要且有用处的资料、源码,大家可前往下载,一起进步。
感谢支持!

浙公网安备 33010602011771号