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:

objCopy_screenshot

 

The full source could be found here.

posted @   opencoder  阅读(299)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示