# Opengl : GLSL utility files

We can create header files in C/C++ which we can include in our project using #include directive but when I use this keyword in my shader it gives the error reserved keyword. If let's say I create an simple text file for adding two numbers and I want to include this file & code in my vertex/fragment shader is it possible?

Yes, With a certain OpenGL extension, that is possible (thanks to NicolBolas for pointing that out). It is pretty much the same as in C++. Let's assume you have a file util.glsl, vertex.glsl and fragment.glsl, all in the same folder. $$^1$$

//in util.glsl
{
return a + b;
}


Then you can call that function, as if it were in your shader file

//in either vertex.glsl or fragment.glsl
#include "util.glsl"

void main()
{
...
}


Your result would then be 3. Of course, if you have the file in a different folder, you need to adjust the path, but again, that is pretty much the same as in C++.

The only caveat is with debugging. Without having tested it right now, as far as I remember compiler errors will not display your util.glsl as the source of your error. Rather it will put the contents of util.glsl at the position, where your include call is and then say you have an error in that line in vertex.glsl / fragment.glsl, so this might be a bit confusing

$$^1$$Actually, this is incorrect (by default at least). In a project we used it like that, but since I did not do that setup myself, I assume it was either setup to work like that by a collegue or by OpenSceneGraph, which we used. In any case, I cannot (yet) answer this myself. I want to add this part, as soon as I understand it myself. Until then, I will simply link to a similar question with answer from NicolBolas, which hints at what you have to do: https://stackoverflow.com/questions/10754437/how-to-using-the-include-in-glsl-support-arb-shading-language-include

• So in the opengl side of creating shaders there are no changes? Feb 23 at 10:08
• No, unless you want to create a shader out of modular functions on the fly. You can do that as well, but then you don't need the include in your shader file anymore. You could for example create a shader out of first the util.glsl and then the fragment.glsl, OpenGL "merges" it into one source code and compiles that. It is not all that different, you get more control about which code to use but you also have more shaders then, which (probably) means you have to switch shaders more often in your render pipeline.
– Tare
Feb 23 at 10:11
• But when creating this utility shader what type should it be?. A vertex shader, a fragment shader? What constant do I specify? Feb 23 at 11:32
• @NicolBolas thanks for the hint. I was not aware of that. I'll adjust my answer.
– Tare
Feb 24 at 11:24