GCC, stringification, and inline GLSL?

genpfault picture genpfault · Dec 14, 2012 · Viewed 7.6k times · Source

I'd like to declare GLSL shader strings inline using macro stringification:

#define STRINGIFY(A)  #A
const GLchar* vert = STRINGIFY(
#version 120\n
attribute vec2 position;
void main()
{
    gl_Position = vec4( position, 0.0, 1.0 );
}
);

This builds and runs fine using VS2010 but fails to compile on gcc with:

error: invalid preprocessing directive #version

Is there a way to use stringification like this in a portable manner?

I'm trying to avoid per-line quotes:

const GLchar* vert = 
"#version 120\n"
"attribute vec2 position;"
"void main()"
"{"
"    gl_Position = vec4( position, 0.0, 1.0 );"
"}"
;

...and/or line continuation:

const GLchar* vert = "\
#version 120\n                                 \
attribute vec2 position;                       \
void main()                                    \
{                                              \
    gl_Position = vec4( position, 0.0, 1.0 );  \
}                                              \
";

Answer

emsr picture emsr · Dec 14, 2012

Can you use C++11? If so you could use raw string literals:

const GLchar* vert = R"END(
#version 120
attribute vec2 position;
void main()
{
    gl_Position = vec4( position, 0.0, 1.0 );
}
)END";

No need for escapes or explicit newlines. These strings start with an R (or r). You need a delimiter (I chose END) between the quote and the first parenthesis to escape parenthesis which you have in the code snippet.