Search code examples
c++visual-studioopenglglew

Why is needed to check if GLAD or GLEW was initialized correctly?


I was setting up opengl using GLFW + GLAD or GLEW (#include glad/glad.h #include <GL/glew.h>). After the function glfwMakeContextCurrent(window); I need to check if GLAD or GLEW was initialized correctly or I will run into exception errors in Visual Studio 2019.

#include <glad/glad.h>
#include <GLFW/glfw3.h>

#include <iostream>
using namespace std;

int main(void) {

GLFWwindow* window;

/* Initialize the library */
if (!glfwInit())
    return -1;

/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
    glfwTerminate();
    return -1;
}

/* Make the window's context current */
glfwMakeContextCurrent(window);

/* Check if GLEW is ok after valid context */
/*if (glewInit() != GLEW_OK) {
    cout << "Failed to initialize GLEW" << endl;
}*/
/* or Check if GLAD is ok after valid context */
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
    cout << "Failed to initialize GLAD" << endl;
    return -1;
}

/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
    /* Render here */
    glClear(GL_COLOR_BUFFER_BIT);
    
    ...
}

glfwTerminate();
return 0;
}

Here I am using GLAD. I really can't understand why I have to check this. Thanks in advance.


Solution

  • Here I am using GLAD. I really can't understand why I have to check this

    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    

    The key point here is not the check, but the call to gladLoadGLLoader which actually initializes GLAD and loads all the GL function pointers. So what you do here is initializing GLAD, and just checking the return value of that function which tells you if GLAD was able to correctly initialize.

    So if you don't want the "check", the correct code would be just

    gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
    

    Ommiting the check is of course not a good idea, because it means that you might attempt to call GL function pointers which might not be loaded, which will most likely crash your application - the same errors you will see when not even attempting to intialize it, as you already did.