Reputation: 1242
I have a binary file which i want to embed directly into my source code, so it will be compiled into the .exe file directly, instead of reading it from a file, so the data would already be in the memory when i launch the program.
How do i do this?
Only idea i got was to encode my binary data into base64, put it in a string variable and then decode it back to raw binary data, but this is tricky method which will cause pointless memory allocating. Also, i would like to store the data in the .exe as compact as the original data was.
Edit: The reason i thought of using base64 was because i wanted to make the source code files as small as possible too.
Upvotes: 15
Views: 9102
Reputation: 399949
There are tools for this, a typical name is "bin2c". The first search result is this page.
You need to make a char
array, and preferably also make it static const
.
In C:
Some care might be needed since you can't have a char
-typed literal, and also because generally the signedness of C's char
datatype is up to the implementation.
You might want to use a format such as
static const unsigned char my_data[] = { (unsigned char) 0xfeu, (unsigned char) 0xabu, /* ... */ };
Note that each unsigned int
literal is cast to unsigned char
, and also the 'u' suffix that makes them unsigned.
Since this question was for C++, where you can have a char
-typed literal, you might consider using a format such as this, instead:
static const char my_data[] = { '\xfe', '\xab', /* ... */ };
since this is just an array of char, you could just as well use ordinary string literal syntax. Embedding zero-bytes should be fine, as long as you don't try to treat it as a string:
static const char my_data[] = "\xfe\xdab ...";
This is the most compact solution. In fact, you could probably use that for C, too.
Upvotes: 6
Reputation: 3715
You can use resource files (.rc). Sometimes they are bad, but for Windows based application that's the usual way.
Upvotes: 4
Reputation: 153977
The easiest and most portable way would be to write a small program which converts the data to a C++ source, then compile that and link it into your program. This generated file might look something like:
unsigned char rawData[] =
{
0x12, 0x34, // ...
};
Upvotes: 11