Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type casting gcc error with const modifier

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

screenshot of text

#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");
...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading