MaiaVictor
MaiaVictor

Reputation: 52967

Why it is necessary to detach and delete shaders after creating them, on OpenGL?

I'm following this tutorial (link), which says you must detach shaders from a program after linking it, and that you must delete them after that.

Making a parallel to compiling C++, intuitively, I imagine that "linking" is the act of actually creating the program (as in, making an executable), - that detaching means somehow removing a pointer to a shader object (which I imagine be similar to an .o), in the program (which is still not very clear - isn't the program a compiled executable at this point? How does it still hold a pointer to something?) - and that deleting is like actually removing those .o's from the folder.

But those are all guesses, so what is actually happening there?

Upvotes: 8

Views: 3148

Answers (2)

Andon M. Coleman
Andon M. Coleman

Reputation: 43319

It might help if you understood that multiple programs can share the same shader. If the mere act of detaching it from a program caused it to become deleted then things like Separate Shader Objects in OpenGL 4.1 would have been implemented much sooner.

You should also be aware that what linking really refers to is more or less validation. When shaders are linked together to create a program, the in/out variables are all connected and used uniforms are assigned identifiers. When the program runs, it populates each stage of the graphics pipeline with a shader. So in effect, all that a program does is encapsulate multiple shader stages.

This is much clearer if you investigate the ARB_separate_shader_objects extension specification, which introduces the concept of program pipeline objects. Instead of having one program with a shader for each stage, you can have one program for each stage. The whole GLSL program scheme has always been a little bit obtuse, in most other APIs you have separate shaders per-stage and there is none of this program linking non-sense.

To use your executable program analogy. GLSL shaders are the actual executables, GLSL programs are effectively job control scripts. Your program is responsible for getting each of your shaders to run in their respective pipeline stage, and serves as the interface for passing them variables (uniforms).

Upvotes: 3

Marcin Łoś
Marcin Łoś

Reputation: 3246

From the OpenGL doc on glDeleteShader:

If a shader object to be deleted is attached to a program object, it will be flagged for deletion, but it will not be deleted until it is no longer attached to any program object, for any rendering context (i.e., it must be detached from wherever it was attached before it will be deleted)

So, it's more like decrementing a reference counter than an actual deletion.

Upvotes: 11

Related Questions