OpenGL Compiled Shader was corrupt

Got it to work.

At first I rewrote the shaders with another editor (text mate) and then it worked sometimes. Then I made sure that it was properly null terminated and it worked every time.

Maybe somehow there were non-printing characters like Andon M. Coleman suggested.


I had the same issue, and discovered that if you use the ' std::stringstream buffer' to read the file, as many code examples on the web use, the method .str().c_str() to get a *ptr needed for glShaderSource, the pointer gets deleted, meaning, you get random linker errors. Here is the work around I created...

int shaderFromFile(const std::string& filePath, GLenum shaderType) {  
  //open file
  std::ifstream f;
  f.open(filePath.c_str(), std::ios::in);
  if(!f.is_open()){
    throw std::runtime_error(std::string("Failed to open file: ") + filePath);
  }

  //read whole file into stringstream buffer
  std::stringstream buffer;
  buffer << f.rdbuf();
  buffer << "\0";
  f.close();
  // need to copy, as pointer is deleted when call is finished
  std::string shaderCode = buffer.str().c_str(); 

  //create new shader
  int ShaderID = glCreateShader(shaderType);

  //set the source code

  const GLchar* code = (const GLchar *) shaderCode.c_str();

  glShaderSource(ShaderID, 1, &code, NULL);
  //compile
  glCompileShader(ShaderID);

  //throw exception if compile error occurred
  GLint status;
  glGetShaderiv(ShaderID, GL_COMPILE_STATUS, &status);
  std::cout << "Status from compile:" << status << "\r\n";
  if (status == GL_FALSE) {
      std::string msg("Compile failure in shader:\n");

      GLint infoLogLength;
      glGetShaderiv(ShaderID, GL_INFO_LOG_LENGTH, &infoLogLength);
      char* strInfoLog = new char[infoLogLength + 1];
      glGetShaderInfoLog(ShaderID, infoLogLength, NULL, strInfoLog);
      msg += strInfoLog;
      delete[] strInfoLog;

      glDeleteShader(ShaderID); ShaderID = 0;
      throw std::runtime_error(msg);
  }

  return ShaderID;
}

Tags:

Opengl