Embed A text file into executable file ~ implement on ubuntu OS

本文介绍如何使用objcopy命令将外部文件嵌入到Linux上的可执行目标文件中。通过CMake链接这些文件变得简单,从源代码访问内容也变得直接。首先创建目标文件,然后将其链接到最终目标,最后从源代码访问外部文件内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

转载于:https://www.cnblogs.com/open-coder/archive/2012/10/28/2743125.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值