C/C++, can you #include a file into a string literal? [duplicate]

I have a C++ source file and a Python source file. I'd like the C++ source file to be able to use the contents of the Python source file as a big string literal. I could do something like this:

char* python_code = "
#include "script.py"
"

But that won't work because there need to be \'s at the end of each line. I could manually copy and paste in the contents of the Python code and surround each line with quotes and a terminating \n, but that's ugly. Even though the python source is going to effectively be compiled into my C++ app, I'd like to keep it in a separate file because it's more organized and works better with editors (emacs isn't smart enough to recognize that a C string literal is python code and switch to python mode while you're inside it).

Please don't suggest I use PyRun_File, that's what I'm trying to avoid in the first place ;)


Solution 1:

The C/C++ preprocessor acts in units of tokens, and a string literal is a single token. As such, you can't intervene in the middle of a string literal like that.

You could preprocess script.py into something like:

"some code\n"
"some more code that will be appended\n"

and #include that, however. Or you can use xxd​ -i to generate a C static array ready for inclusion.

Solution 2:

This won't get you all the way there, but it will get you pretty damn close.

Assuming script.py contains this:

print "The current CPU time in seconds is: ", time.clock()

First, wrap it up like this:

STRINGIFY(print "The current CPU time in seconds is: ", time.clock())

Then, just before you include it, do this:

#define STRINGIFY(x) #x

const char * script_py =
#include "script.py"
;

There's probably an even tighter answer than that, but I'm still searching.