c++openglvisual-studio-2015glfwglad

GLAD failing to initialize


I'm having a problem where the following lines of code always print "Failed to initialize glad" and then exits the program:

if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
    std::cout << "Failed to initialize GLAD" << std::endl;
    return -1;
}

I have been using https://learnopengl.com/ as a guide and have been following the steps in the getting started section. I am writing this using Visual Studio, I have moved the glad.c source file into the build to get this working and added the header files to the same location where I specified the GLFW header would be, but I haven't been able to find anyone with a problem similar to mine.

Commenting out return -1; line results in an access violation exception, so it is definitely here that the program is having trouble.

Here is the entire program in case there is something else I am missing:

#include "stdafx.h"
#include <GLFW/glfw3.h>
#include <glad/glad.h>
#include <iostream>

using namespace std;

void init_glfw();

void framebuffer_size_callback(GLFWwindow*, int, int);

int main(int argc, char **argv)
{
    init_glfw();

    GLFWwindow* window = glfwCreateWindow(800, 600, "Lab3", NULL, NULL);

    if (window == NULL)
    {
        cout << "Failed to create GLFW window" << endl;
        glfwTerminate();
        return -1;
    }


    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    glViewport(0, 0, 800, 600);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);


    while (!glfwWindowShouldClose(window))
    {
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

void init_glfw()
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    glViewport(0, 0, width, height);
}

Solution

  • You never made your GL context current via glfwMakeContextCurrent(). Unlike other GL windowing frameworks GLFW doesn't leave the GL context current when glfwCreateWindow() succeeds.

    Call glfwMakeContextCurrent() after glfwCreateWindow() succeeds:

    GLFWwindow* window = glfwCreateWindow(800, 600, "Lab3", NULL, NULL);
    if (window == NULL)
    {
        cout << "Failed to create GLFW window" << endl;
        glfwTerminate();
        return -1;
    }
    
    glfwMakeContextCurrent( window );
    
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }