Marco La Rosa
Marco La Rosa

Reputation: 43

How to store a file inside an executable

I was wondering if it is possible to store for example an image or other file inside an executable and then work with that at runtime (for example showing the image on the screen).

I know auto-extractable archives exists and I also wonder how those work.

Finally, how can it be implemented using C/C++?

I'm working in a windows 10 x64 enviroment but I'm also interested in the linux enviroment

Thanks in advance for the help

Upvotes: 3

Views: 555

Answers (2)

eerorika
eerorika

Reputation: 238281

Files are just arrays of bytes. So, to contain a file within an executable, you simply need an array that contains the bytes of the file:

unsigned char file_content[] = {
  0x23, 0x20, 0x46, 0x6c, ...
};

Tools exist to generate such declaration from an input file (xxd -i). It's also fairly trivial to write such tool yourself.

Another technique is to embed the file at linking stage. Drawback of this approach is that it is highly toolchain specific.


However, do consider that reading a separate file at runtime is usually simpler and provides more flexibility.


There is also a proposal to add standard function to do this P1040R4, which may be available in a future C++ standard

Upvotes: 3

tenfour
tenfour

Reputation: 36896

Embedded resources are very common, and part of the PE file format. If you're using Visual Studio for example, you can add any binary data you want as a resource. It will be compiled using rc.exe, the resource compiler, and linked into the output binary.

You access these resources with the FindResource, LoadResource, and LockResource winapi calls.

Upvotes: 0

Related Questions