-1

I'm having an issue with compiling GLSL code. When I try to print whether my shader was compiled correctly by using glGetShaderiv(), my program sometimes prints out the wrong result. For example, with this shader (test.vert):

#version 410

void main()
{

}

and using the following code:

#include <GL\glew.h>
#include <GLFW\glfw3.h>

#include <iostream>
#include <fstream>
#include <string>

int main() {
    glfwInit();
    GLFWwindow* window = glfwCreateWindow(200, 200, "OpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);

    glewInit();

    std::string fileText = "";
    std::string textBuffer = "";
    std::ifstream fileStream{ "test.vert" };
    while (fileStream.good()) {
        getline(fileStream, textBuffer);
        fileText += textBuffer;
    }

    GLuint vertShaderID = glCreateShader(GL_VERTEX_SHADER);
    const char* vertShaderText = fileText.c_str();
    glShaderSource(vertShaderID, 1, &vertShaderText, NULL);
    glCompileShader(vertShaderID);

    GLint vertCompiled;
    glGetShaderiv(vertShaderID, GL_COMPILE_STATUS, &vertCompiled);
    if (vertCompiled != GL_TRUE) {
        std::cerr << "vert shader did not compile." << std::endl;
    }

    glfwTerminate();

    system("PAUSE");

    return 0;
}

the program outputs that the shader did not compile, although I believe that it should have. I have tested many other shader programs, for example by putting a random 'a' or another letter in the middle of a word in the shader code, and I'm still getting incorrect outputs (this test had no error output).

I have also tried printing out the value of 'fileText' and it was correct (the same as in test.vert). What am I doing wrong?

I'm using a 64-bit Windows system, the supported OpenGL version is 4.40.

kneedhelp
  • 375
  • 3
  • 15
  • 2
    1) Does `fileText` really contain the exact same content as your file including linebreaks? For me it looks as if your shader loader would discard linebreaks. 2)Why not check [`glGetShaderInfoLog`](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGetShaderInfoLog.xhtml) in case of an error to see what problem the compiler complains about? – BDL May 31 '17 at 07:58

1 Answers1

3

getline clips off the \n. That means that your entire file will not have any line breaks. It's all on one line, and therefore looks like this:

#version 410 void main() { }

That's not legal GLSL.

Please stop reading files line-by-line. If you want to read an entire file, then read the entire file.

Nicol Bolas
  • 378,677
  • 53
  • 635
  • 829
  • This was part of my issue. I was also having a problem with trailing garbage at the end of strings which I was able to fix using the code in [this question](https://stackoverflow.com/questions/16624318/glsl-weird-syntax-error). Thank you. – kneedhelp May 31 '17 at 17:01