I’m playing around with OpenGL and decided to implement a function that would load shader source code from file to string.
OpenGL is expecting to get const char*
.
So here is the function I got:
const char* string_from_file(const char* filename) {
FILE* f = fopen(filename, "r");
if (f == NULL) {
fprintf(stderr, "Error while trying to open %s file\n", filename);
exit(1);
}
char* buf = (char*) malloc(MAX_SHADER_FILE_SIZE);
char c;
size_t i = 0;
while((c = fgetc(f)) != EOF) {
buf[i] = c;
i++;
}
return buf;
}
Error I’m getting from gcc:
#include <GLFW/glfw3.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SHADER_FILE_SIZE 200
void framebuffer_size_callback(GLFWwindow *window, int width, int height);
void processInput(GLFWwindow *window);
void _print_shader_info_log(GLuint shader_index);
const char* string_from_file(const char *filename);
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
const char *vertexShaderSource = string_from_file("src/shaders/main_vert.glsl");
const char *fragmentShaderSource = string_from_file("src/shaders/main_frag.glsl");
If compiled with g++ there is no error, it builds and runs.
So error says: initializer element is not compile-time constant
. Why does it have to be compile-time constant? Isn’t const type*
supposed to mean: the thing that this is pointed to should not be altered? Why is this error not there if compiled with g++?
>Solution :
This has nothing to do with your variable being const
. It’s because you’re trying to call a function from the global scope, outside of any function, which you absolutely can’t do in C. It will probably work better if you do it like:
const char *vertexShaderSource;
...
int main(void)
{
vertexShaderSource = string_from_file("src/shaders/main_vert.glsl");
...
}