View Full Version : Correct way to delete shader programs

04-10-2013, 11:41 AM
I have a function createShader inside a Shader class that takes the filepaths of two vertex and fragment shaders as arguments, loads and compiles them, and uses glCreateProgram to create a shader program out of them. The latter part looks like this:

char const * vsSourcePtr = vsCode.c_str();
glShaderSource(vsId, 1, &vsSourcePtr, NULL);

char const * fsSourcePtr = fsCode.c_str();
glShaderSource(fsId, 1, &fsSourcePtr, NULL);

this->progId = glCreateProgram();
glAttachShader(this->progId, vsId);
glAttachShader(this->progId, fsId);
glBindAttribLocation(this->progId, 0, "in_Position");


The Shader class also has a method for deleting the generated shaders when the program is closed:

void Shader::deleteShader(){
My question is, is it correct to put the two glDeleteShader calls where they are? Can I delete the vertex and fragment shaders once I've already linked the shader program?

If so, what about glDetachShader? Does that need to go in my deleteShader function?

This seems to work without errors, but there may be a memory leak somewhere in the program, and I'm wondering if this is it.

Alfonse Reinheart
04-10-2013, 07:16 PM
It's unlikely that this is a leak, but the shader object will not actually be deleted until it us unattached from all programs. When you delete the program, all attached shaders become unattached, so it is only then that they will be deleted.

In general, you should detach shaders immediately after linking.

04-10-2013, 09:37 PM
So it's okay to detach the shaders (and then, I presume, delete them) before the program itself is ever used? The program will still function correctly, even though its shaders have been detached?

That confuses me as to what a shader program actually is. What's the relationship between shaders and programs after the shaders have been linked, and how come I can detach them with no effect on the program?

Alfonse Reinheart
04-10-2013, 09:58 PM
The only reason to attach shaders to programs is to perform a link. Once that's done, the program now has all of the shader stage information.

The OpenGL compilation model mirrors the standard C/C++ compilation model. You have source code files that you compile into object files. You then link those files into an executable.

OpenGL has shader source code files that you compile into shader objects. You then link those shader objects into a program object.

You don't need to ship your .o files with your executable. Just as you don't need the shader objects after linking them into a program.