Skip to main content
1 of 2
datenwolf
  • 163.1k
  • 13
  • 197
  • 316

glShaderSource( m_nShaderId, nNumLines, (const GLchar**)ppSrc, (GLint*) pnSrcLineLen );

I know the signature of glShaderSource looks tempting to send each line of the shader separately. But that's now what it's meant for. The point of being able to send is multiple arrays is so that one can mix multiple primitive shader sources into a single shader, kind of like include files. Understanding this, makes it much simpler to read in a shader file – and avoids such nasty bugs.

Using C++ you can do it much nicer and cleaner. I already wrote the follwing in Getting garbage chars when reading GLSL files


You're using C++, so I suggest you leverage that. Instead of reading into a self allocated char array I suggest you read into a std::string:

#include <string> #include <fstream> std::string loadFileToString(char const * const fname) { std::ifstream ifile(fname); std::string filetext; while( ifile.good() ) { std::string line; std::getline(ifile, line); filetext.append(line + "\n"); } return filetext; } 

That automatically takes care of all memory allocation and proper delimiting -- the keyword is RAII: Resource Allocation Is Initialization. Later on you can upload the shader source with something like

void glcppShaderSource(GLuint shader, std::string const &shader_string) { GLchar const *shader_source = shader_string.c_str(); GLint const shader_length = shader_string.size(); glShaderSource(shader, 1, &shader_source, &shader_length); } 

You can use those two functions together like this:

void load_shader(GLuint shaderobject, char * const shadersourcefilename) { glcppShaderSource(shaderobject, loadFileToString(shadersourcefilename)); } 
datenwolf
  • 163.1k
  • 13
  • 197
  • 316