2

Can you write OpenGL shader in a different file and later link it to the program? and if it's possible how? writing OpenGL shader in string makes my code messy.

Here is example code for shaders:

const char* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec3 aColor;\n" "\n" "out vec3 ourColor;\n" "uniform vec2 angleValues;\n" "\n" "void main()\n" "{\n" "gl_Position = vec4(aPos.x * angleValues.x - aPos.y * angleValues.y, aPos.y * angleValues.x + aPos.x * angleValues.y , aPos.z, 1.0);\n" "ourColor = aColor;\n" "}\n"; const char* fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "in vec3 ourColor;\n" "\n" "void main()\n" "{\n" "FragColor = vec4(ourColor, 1.0);\n" "}\n"; 
2
  • 2
    "writing OpenGL shader in string makes my code messy." C++11 raw string literals make it much cleaner, no need for all the \n's. Commented Aug 23, 2022 at 15:19
  • 2
    yes, you can; it's very easy to read a file into a const char*. Commented Aug 23, 2022 at 15:27

1 Answer 1

2

Yes, you can have files like my_shader.vs or my_fragment.fs and link them like in this Shader class

Just initialize it like this:

shader = Shader("./shaders/my_shader.vs", "./shaders/my_fragment.fs"); 
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, btw, can u tell me how to link those files into shader class?
Just use the example initialization I've given. Make sure the files are there and the path is proper, use absolute path if needed. If you need more documentation look at this example: learnopengl.com/code_viewer_gh.php?code=src/1.getting_started/…
@NikoMolecule If these helped can you please accept my answer?
This isn't linked - you made the program load the shader at run-time.
@Turgut yes it helped, i forgot to accept it
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.