Search code examples
c++openglopengl-3

OpenGL3: Clean-up after failed shader compilation


When compiling a vertex- or fragment-shader, should one call the glDeleteShader() function on the shader which failed to compile or is it only applicable to successfully compiled shaders?

For instance, using the shader

const GLchar* vertexSource =
    "#version 150 core\n"
    "in vec2 position;" // Vertices specified in 2 dimensions: (X, Y)
    "void main()"
    "{"
    "    gl_Position = vec4(position, 0.0, 1.0)"  // Removed semicolon here
    "}";

which is broken due to a missing semi-colon, in conjunction with:

GLuint vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);

glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);

GLint success;

glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);

if (!success) {
    GLchar infoLog[512];
    glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
    std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}

will trigger the if-clause due to a syntax-error: error: syntax error, unexpected '}', expecting ',' or ';'.

I have tried adding glDeleteShader(vertexShader); inside the if-clause as well as left it out, but cannot discern any difference in how the program behaves as it exits.

Should the shader be deleted?


Solution

  • A shader object exists whether it was successfully compiled or not. So yes, you should delete it even if it failed compilation.

    Shader objects actually have storage for the shader strings you provided in glShaderSource (you can retrieve them with glGetShaderSource). So while they aren't GPU objects, they're not exactly lightweight.

    but cannot discern any difference in how the program behaves as it exits.

    Nor would you expect to. It would be no different from allocating a char* string and then forgetting to delete it by the time the program exits. You won't notice the small memory that you leaked one time.