Embed A text file into executable file ~ implement on ubuntu OS
With the objcopy command, we could embed some external files into the executable target file on Linux. Here objcopy used as a tool that convert the a external file into some a target file with some segments only, so that the linker could combine all those target files into the executable file.
Create the target file with objcopy
With the vim, we could create a text file named string.txt and write some thing into it, then save it. Then under the command line, type in (Not only text file, you could also convert the image file or other type of files, please do not make the executable file too large):
$objcopy –I binary –O elf32-i386 –B i386 string.txt string.o
We could check the segment name, with the following command:
$objdump –ht string.o
Link the target file into the final target with the CMake
With the CMake tool, link the external object become very easy, what we need to do is append the target files in the end of the ADD_EXECUTABLE command, just as following:
ADD_EXECUTABLE(objcopy_demo ${SRC_LIST} string.o)
Access the external file content from the source code
With the objdump command, you already know the symbol of the segment, you could declare some symbols like following:
extern "C"
{
extern char _binary_string_txt_start;
extern char _binary_string_txt_end;
};
And you could access the content as following:
char* pContent = &_binary_string_txt_start;
printf("string.txt : %s\n", pContent);
As you see, it seems a ‘\0’was append at the end of the file content.
After all of the above works done, now you could compile & link the whole program. Then run it. You will see some thing like this:
The full source could be found here.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了