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!

6
  • Have seen this on SO before... looking. Commented Dec 16, 2012 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. Commented Dec 16, 2012 at 21:24
  • stackoverflow.com/questions/410980/… related, not exactly what I was looking for. Commented Dec 16, 2012 at 21:25
  • What is your target OS? If it's Windows you can use raw resources linked into your project. You can access them as usual (example). Commented Dec 16, 2012 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 Commented Dec 16, 2012 at 21:37

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.