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

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


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.


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) #xconst char * script_py =#include "script.py";

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


The best way to do something like this is to include the file as a resource if your environment/toolset has that capability.

If not (like embedded systems, etc.), you can use a bin2c utility (something like http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c). It'll take a file's binary representation and spit out a C source file that includes an array of bytes initialized to that data. You might need to do some tweaking of the tool or the output file if you want the array to be '\0' terminated.

Incorporate running the bin2c utility into your makefile (or as a pre-build step of whatever you're using to drive your builds). Then just have the file compiled and linked with your application and you have your string (or whatever other image of the file) sitting in a chunk of memory represented by the array.

If you're including a text file as string, one thing you should be aware of is that the line endings might not match what functions expect - this might be another thing you'd want to add to the bin2c utility or you'll want to make sure your code handles whatever line endings are in the file properly. Maybe modify the bin2c utility to have a '-s' switch that indicates you want a text file incorportated as a string so line endings will be normalized and a zero byte will be at the end of the array.