Shaders & programsGL 2.0

glShaderSource

Gives a shader object its GLSL source code.

Signature

void glShaderSource(GLuint shader, GLsizei count,
                    const GLchar **string, const GLint *length);

How it works

Copies the source text into the shader. Nothing is compiled yet. The source can be passed as several strings which are concatenated in order — handy to prepend a #version line or #define flags to a shared file.

Parameters

shaderGLuint

Shader created with glCreateShader.

countGLsizei

Number of strings in the array.

stringconst GLchar **

Array of pointers to source strings. For one string pass &src.

lengthconst GLint *

Length of each string, or nullptr if they are null-terminated.

Tips & pitfalls

  • Do not pass a temporary: std::string(...).c_str() dies before the call returns. Keep the std::string alive in a variable.

Errors

When the call is invalid it does nothing and sets an error, which glGetError returns:

GL_INVALID_VALUE
count is negative or shader is not a valid ID.

Example

example.cpp
1std::string code = readFile("shader.vert");
2const char* src = code.c_str();
3glShaderSource(vs, 1, &src, nullptr);
Official Khronos documentation