Recently I needed to access a text file containing a database schema in my code. Now this schema is tied to my application and should ideally be bundled with the exe somehow.
Having a separate file that the app reads at startup just introduces another point of failure and the file was too large to easily embed as C-strings. Plus C-Strings are a headache to edit (escape sequences) whenever we need to change the schema.
The ideal solution for this, of course, was to use windows
resources, but I needed to bundle the resource in a
.lib and not an
.exe. I couldn't figure out how to get
rc to co-operate with my linker so after spending about half a day on that I gave up.
I had almost resigned myself to needing a separate file when I found this really
really cool solution! Ready? Here goes...
THE MAGIC OF OBJCOPY
Objcopy is this really cool utility from GNU (availble on cygwin). Basically it can convert object files from one format to another. It also can - wait for it - convert any arbitary file into .obj format!
Problem solved!
Well almost ... :-)
We still have to access it from our application, so I checked the exported symbols and lo and behold - it gave me the symbols I needed to access the data as a stream of characters.
Putting it all together:
- Run objcopy:
objcopy --input-target binary --output-target pe-i386 --binary-architecture i386 MYFILE.ext OUTFILE.obj
- Run dumpbin to check the exported symbols:
COFF SYMBOL TABLE
000 00000000 SECT1 notype External | _binary_myfile_ext_start
001 00000E40 SECT1 notype External | _binary_myfile_ext_end
002 00000E40 ABS notype External | _binary_myfile_ext_size
- Access in code:
extern "C" char binary_myfile_ext_start;
extern "C" char binary_myfile_ext_end;
...
char* p = &binary_dbinfo_tdl_start;
while (p != &binary_dbinfo_tdl_end) {
// Do whatever with *p
++p;
}
Neat yes? :-)