GLFW窗口打开一秒后自动关闭的原因排查求助
问题解决:GLFW窗口打开一秒即关闭
核心问题
你的代码里主循环用了if判断而非while循环,这会导致循环体只执行一次就直接进入glfwTerminate(),程序随即退出,窗口也就瞬间关闭了。
修改后的完整代码
#include <GL/glew.h> #define GLFW_DLL #include <GLFW/glfw3.h> #include <stdio.h> #include <stdbool.h> // function declarations void framebuffer_callback(GLFWwindow* window, int width, int height); void process_input(GLFWwindow* window); int main(void) { // initialize GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW.\n"); glfwTerminate(); return -1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // __APPLE__ // create the window GLFWwindow* window = glfwCreateWindow(800, 600, "Revised", NULL, NULL); if (window == NULL) { printf("Window failed.\n"); glfwTerminate(); return -1; } // put GLFW on the main thread and bind a frame buffer function glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_callback); // load all OpenGL function pointers GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "Failed to load GLEW: %s\n", glewGetErrorString(err)); return -1; } printf("GLEW version: %s\n", glewGetString(GLEW_VERSION)); // 修正:将if改为while,实现持续运行的主循环 while (!glfwWindowShouldClose(window)) { // 处理输入 process_input(window); // 清空颜色缓冲,避免窗口显示异常(可选但推荐) glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // 处理事件交换缓冲 glfwPollEvents(); glfwSwapBuffers(window); } glfwTerminate(); return 0; } // function definitions void framebuffer_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void process_input(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } }
额外说明
- 主循环必须用
while才能持续监听窗口事件、更新画面,直到用户触发关闭操作(比如按ESC)。 - 添加
glClearColor和glClear是为了给窗口设置一个初始背景色,否则窗口可能会显示随机的垃圾像素,这是OpenGL渲染的基本步骤。 - 确认Code::Blocks中已正确链接GLFW和GLEW库,确保编译时没有链接错误(如果之前调整过库,建议重新检查库路径和链接选项)。
内容的提问来源于stack exchange,提问作者Chillzy
相关产品推荐
相关产品推荐

