View Full Version : Does glDeleteProgram free shaders?

09-16-2013, 08:49 AM
In my program I have a function to compile shaders which creates each shader index variable locally to be binded to the program object which it returns like so:


GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

// compile each shader

programObject = glCreateProgram();

glAttachShader(programObject, vertexShader);
glAttachShader(programObject, fragmentShader);


glGetProgramiv(programObject, GL_LINK_STATUS, &linked);
if(!linked) return 0;

return programObject;

So that I can then do:


int menuShader = 0;
short initMenu(void) {
menuShader = compileShaders(...);
void renderMenu(void) {
// render

Now to deinit the menu, is calling:

glDeleteProgram(1, menuShader);

Enough? Will it free my vertex and fragment shaders as well or just free the program object? If not, does that mean that I have to make vertexShader and fragmentShader global variables so that I can free them as well in the deinit routine?

09-16-2013, 09:47 AM
The shader objects are needed only for linking the program, you can delete them after you linked the program.

09-16-2013, 10:30 AM
To be more precise: the shader object contains the raw text you passed in. The program object contains the compiled executable corresponding to that text.

These objects are all ref-counted. When you create a shader, the initial refcount is one. When you attach a shader to a program, the refcount is now two. So, deleting the program decrements the refcount because the attachment is going away, but the shader won't be deleted until the refcount goes to zero, i.e. you must also delete the shader object yourself.

If you want to ensure that all shader objects are deleted, you should detach and delete shader objects after linking the program. Merely deleting the shader isn't enough because the attachment still maintains a refcount (you can still glGetProgram(...GL_ATTACHED_SHADERS...) for example.)

Or to simplify this whole process, use SSO's glCreateShaderProgram (http://www.opengl.org/sdk/docs/man/xhtml/glCreateShaderProgram.xml). See what that pseudo code does?