5

I'd like to hardcode large sets of data (integer arrays of varying length, a library of text strings, etc) directly into an executable file, so there are no additional files.

My question is, what is the most practical and organized method for doing this in C++? Where would I place the data, in terms of header or source files? What structure should I use?

I realize this isn't the accepted way of dealing with data. But humour me!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Anne Quinn
  • 12,609
  • 8
  • 54
  • 101
  • Have seen this on SO before... looking. – djechlin Dec 16 '12 at 21:24
  • try putting it in a different .cpp file, for example, `resources.cpp`, then make it `extern` and give it a header file. –  Dec 16 '12 at 21:24
  • http://stackoverflow.com/questions/410980/include-a-text-file-in-a-c-program-as-a-char related, not exactly what I was looking for. – djechlin Dec 16 '12 at 21:25
  • What is your target OS? If it's Windows you can use [raw resources](http://msdn.microsoft.com/ru-ru/library/windows/desktop/aa381039(v=vs.85).aspx) linked into your project. You can access them as usual ([example](http://msdn.microsoft.com/en-us/library/cc194809.aspx)). – Stan Dec 16 '12 at 21:32
  • @stan - I'm compiling on windows, but I'd need to switch compilers at some point to make mac/debian binaries I'm afraid – Anne Quinn Dec 16 '12 at 21:37
  • You might want to have a look at the [Qt Resource System](http://doc.qt.digia.com/qt/resources.html), it's a good example of doing this in a portable and organized way. In short, it converts files to char arrays that get built into the binary and uses static initializers to set up a central registry of files that have been compiled in – je4d Dec 16 '12 at 22:13

2 Answers2

8

For both C++ and C, you may use header file to put declarations for these variables, and then place actual initialization code into .c (or .cc) file. Both C and C++ have decent initializers syntax. For example:

mydata.h:

extern int x;
extern int a[10];
extern unsigned char *s;

mydata.c:

#include "mydata.h"
int x = 123;
int a[10] = {1,2,3,4,5,6,7,8,9,10};
unsigned char *s = "mystring";

then main.c will have:

#include "mydata.h"
#include <stdio.h>

int main(const int argc, char *argv[])
{
  printf("%d, %d, %s\n", x,a[5],s);
}

test run looks like this:

$gcc -o main main.c mydata.c
$ ./main 
123, 6, mystring

Now, to really get organized, one would write Perl/Python/PHP script to generate such formed files from your datasources, like SQL database of CSV files.

vleo
  • 351
  • 3
  • 4
1

Try this:

http://sourceforge.net/projects/bin2obj/

Convert your data to an OBJ and link into your project.

Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67