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";
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 2
    "writing OpenGL shader in string makes my code messy." [C++11 raw string literals make it much cleaner](https://stackoverflow.com/a/13872584/44729), no need for all the `\n`'s. – genpfault Aug 23 '22 at 15:19
  • 2
    yes, you can; it's very easy to read a file into a `const char*`. – new Q Open Wid Aug 23 '22 at 15:27

1 Answers1

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");
Turgut
  • 711
  • 3
  • 25