I would like to write something in a file (let's call it foo.cpp
) and include it as a string into my program at compile time, similar to the way #include
does it.
Right now I'm using this C preprocessor #define
:
#define toString(src) #src
to convert a bunch of code to a string, used as in this example:
const char* str = toString(
int x;
void main(){}
);
You can read about macro stringification there if you want.
I would like to move that code to an external file, which would be "linked" at compile-time. I don't want the file to have to be distributed with the program, which would be the case if I were to read it a run-time.
I tried to use an #include
directive as shown below, but the compiler refused it:
const char* str = toString(
#include "foo.cpp"
);
g++
seems to be completely confused, but clang++
gave me this error:
error: embedding a #include directive within macro arguments is not supported
Does anyone know if/how this can be done?
Note: I'm using this to write my GLSL shaders, although I doubt this information is of any use.
PS: Before you tell me this is a duplicate of this question, putting my code in a giant string in its own file or using an external tool (eg. xxd
) to dump its hex representation are not "solutions" for me, as they are not better (ie. easier/cleaner) than my current method.
Update, a few years later:
I just realized I never got to answer this question as it was closed as duplicate.
I found the answer I was looking for when I saw this commit, itself based on a comment on this article, and have been using it ever since.
In a nutshell, a small assembly file includes the files you want and exposes them under a given NAME
, with the three variables NAME_begin
, NAME_end
and NAME_len
allowing you to access their contents from your C code.
This way, you have a normal file containing nothing but the code you want, and it gets read automatically at compile time, instead of having to read it at runtime or having to jump through xxd
hoops.