GCC、字符串化和内联 GLSL?

2021-12-18 00:00:00 opengl gcc c++ glsl c-preprocessor

我想使用宏字符串化内联声明 GLSL 着色器字符串:

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

#define STRINGIFY(A)  #A
const GLchar* vert = STRINGIFY(
#version 120

attribute vec2 position;
void main()
{
    gl_Position = vec4( position, 0.0, 1.0 );
}
);

使用 VS2010 构建并运行良好,但无法在 gcc 上编译:

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?

我试图避免每行引号:

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

...和/或续行:

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

推荐答案

你会使用 C++11 吗?如果是这样,您可以使用 原始字符串文字:

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

无需转义或显式换行.这些字符串以 R(或 r)开头.您需要在引号和第一个括号之间使用分隔符(我选择了 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.

相关文章