| Tuesday May 31st 2016

Embedding a File in an Executable, aka Hello World v5967

Linux Journal LogoI recently had the need to embed a file in an executable. Since I’m working at the command line with gcc, et al and not with a fancy RAD tool that makes it all happen magically it wasn’t immediately obvious to me how to make this happen. A bit of searching on the net found a hack to essentially cat it onto the end of the executable and then decipher where it was based on a bunch of information I didn’t want to know about. Seemed like there ought to be a better way…

And there is, it’s objcopy to the rescue. objcopy converts object files or executables from one format to another. One of the formats it understands is “binary”, which is basicly any file that’s not in one of the other formats that it understands. So you’ve probably envisioned the idea: convert the file that we want to embed into an object file, then it can simply be linked in with the rest of our code.

Let’s say we have a file name data.txt that we want to embed in our executable:

  # cat data.txt
  Hello world

To convert this into an object file that we can link with our program we just use objcopy to produce a “.o” file:

  # objcopy --input binary \
            --output elf32-i386 \
            --binary-architecture i386 data.txt data.o

Read more…

Related Posts: On this day...

Leave a Reply

You must be logged in to post a comment.