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

Joseph Garvin picture Joseph Garvin · Aug 7, 2009 · Viewed 21.5k times · Source

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 ;)

Answer

bdonlan picture bdonlan · Aug 7, 2009

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.