Ways to embed files in executables¶
Hey folks!
Recently while working on a project, I’ve got distracted yet again. I needed to find a way to embed multiple scripts inside a C program that makes use of the Lua interpreter to provide a configuration system.
There are several ways to embed resources in an executable.
C23 introduced a new pre-processor directive #embed
It provides a standard way to include data in an executable.
However, the project I am working uses a much older standard.
Another technique is the xxd
utility.
It provides the -i
option which generates a C array of unsigned chars
from a supplied file
echo hello! > testing.txt
xxd -i testing.txt testing.h
cat testing.h
unsigned char testing_txt[] = {
0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0x0a
};
unsigned int testing_txt_len = 7;
It’s a valid method that is useful for cases when a single file needs to be included.
One significant limitation of this approach is that resources can not be resolved at runtime. One has to maintain an array of references to each resource.
Some Editors/IDEs might not digest large C arrays when the file is opened a freeze might occur.
That being said, it is certainly possible write a script around xxd
That generates an index of each resource that was converted.
But then there is also a technique using assembly files.
I finally decided to go with objcopy
which can convert anything into an object file.
The rest is achieved with some good’ol shell scripting - that will raise many ‘legacy warnings’ in ShellCheck. :)
Microsoft Github: https://github.com/etag4048/binembed
Or alternatively get the tar: https://tagirov.ch/software/binembed_current.tar.gz