I’m reading both the vertex shader and the fragment shaders from files.
Here’s the function I use for creating the shaders:
GLuint createShaderFromFile(GLenum shaderType, char* fileName)
{
printf("Loading shader file %s
", fileName);
// Create shader object
GLuint shader = glCreateShader(shaderType);
if (!shader || glGetError() != GL_NO_ERROR) {
fprintf(stderr, "Error: Unable to create shader object
");
return 0;
}
// Load source file from disk
FILE* f = fopen(fileName, "rt");
if (!f) {
fprintf(stderr, "Error: Unable to open file %s
", fileName);
return 0;
}
fseek(f, 0, SEEK_END);
int length = ftell(f);
fseek(f, 0, SEEK_SET);
char* buffer = new char[length + 1];
fread(buffer, 1, length, f);
fclose(f);
buffer[length] = '\0';
const GLchar* strings[] = { buffer };
// Feed source code into shader object
glShaderSource(shader, 1, strings, NULL);
delete[] buffer;
// Compile shader
printf("Compiling shader...
");
glCompileShader(shader);
// If compilation produced any messages, print them
GLchar log[16384];
GLsizei logLength;
glGetShaderInfoLog(shader, sizeof(log) - 1, &logLength, log);
if (logLength) {
printf("%s", log);
}
// Check if compilation was successful
GLint compileStatus;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus);
if (compileStatus != GL_TRUE) {
fprintf(stderr, "Error: Shader compilation failed!
");
return 0;
}
else {
printf("Done.
");
}
return shader;
}
This is originally a function written by someone else in C, that I have just pimped up a bit by changing malloc to new[] and free to delete[] since I’m programming in C++.
I don’t know how much information I need to provide for it to be possible to find the bug, but for example the shader file
void main() { gl_Position = gl_Vertex; }
(no newline) compiles while the shader file
void main() { gl_Position = gl_Vertex; }
(one newline) crashes upon compilation.