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.