Search code examples
c++windowglfw

glfw how to destroy window in mainloop


I am trying to develop a program using glfw where the window closes in the main loop. However, I get this weird run time error:

X Error of failed request:  GLXBadDrawable
  Major opcode of failed request:  152 (GLX)
  Minor opcode of failed request:  11 (X_GLXSwapBuffers)
  Serial number of failed request:  158
  Current serial number in output stream:  158

Here is the code I'm trying to run

#include <GL/glfw3.h>

int main()
{
    GLFWwindow* window;

    if(!glfwInit())
        return -1;

    window = glfwCreateWindow(400, 400, "window", nullptr, nullptr);

    if(!window)
    {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);

    while(!glfwWindowShouldClose(window))
    {
        glfwDestroyWindow(window);

        glfwSwapBuffers(window);

        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

Is there any way to destruct the window from inside the main loop?


Solution

  • Yes, you can call glfwDestroyWindow in the main loop. Here's how I did it.

    #include <GLFW/glfw3.h>
    
    int main()
    {
        GLFWwindow* window;
        
        if(!glfwInit())
            return -1;
    
        window = glfwCreateWindow(400, 400, "My Window", NULL, NULL);
    
        if(!window)
        {
            glfwTerminate();
            return -1;
        }
    
        glfwMakeContextCurrent(window);
    
        while(!glfwWindowShouldClose(window))
        {
            if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
            {
                glfwDestroyWindow(window);
                break;
            }
    
            glfwSwapBuffers(window);
    
            glfwPollEvents();
        }
    
        glfwTerminate();
        return 0;
    }
    

    Press the Q key to destroy the window. Try running this code to see if it will work. I ran this code and the process simply returned 0 without printing any error messages. I don't see why it shouldn't work for you.