poetryofruins poetryofruins - 1 month ago 10
C Question

Why do I use this notation to store shader's source code in a variable in C/C++?

I am reading the OpenGL Super Bible 7th edition and in one of the earliest chapters there is an example of shader source code written like this:

static const GLchar * vertex_shader_source[] =
{
"#version 450 core \n"
" \n"
"void main(void) \n"
// ... etc ...
};


Why is this code stored in an GLchar pointer source array variable?

I mean, isn't
GLchar*
alone enough to store a certain number of consecutive bytes? i.e. why not:

static const GLchar* source = ...


or:

static const GLchar source[] = ...


Why do we have to use both
*
and
[]
?

I understand
static const
, so that's not a problem BTW.

Answer

Since a shader object can (and usually does) consist of multiple shaders, the interface to glShaderSource takes an array of C-style strings. This is reflected in the source code you are studying (that happens to contain a single shader).

In other words, code usually looks like this:

static const GLchar * vertex_shader_source[]{
    "#version 450 core                  \n"
    "                                   \n"
    "void main(void)                    \n",
    // ... etc ...
    "#version 450 core                  \n"
    "                                   \n"
    "void main(void)                    \n",
    // ... etc ...
};

GLuint vshandle = glCreateShader( GL_VERTEX_SHADER );
glShaderSource( vshandle,
                sizeof( vertex_shader_source ) / sizeof( vertex_shader_source[0] ),
                vertex_shader_source,
                nullptr );
glCompileShader( vshandle );
Comments