这是我的代码:
#include <iostream>
#include <GLFW/glfw3.h>
int main(void){
GLFWwindow* window;
if(!glfwInit()){
std::cout << "Failed to initialize GLFW!" << std::endl;
return -1;
}
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if(!window){
glfwTerminate();
std:: cout << "Failed to initialize Window!" << std::endl;
return -1;
}
glfwMakeContextCurrent(window);
while(!glfwWindowShouldClose(window)){
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
我成功地链接并编译了它,但我遇到了运行时错误它说glfw初始化失败。我试图在C中使用glfw,但这个错误显示
Wayland: Failed to connect to display
The GLFW library is not initialized
main: ./src/posix_thread.c:64: _glfwPlatformGetTls: Assertion `tls->posix.allocated == GLFW_TRUE' failed.
Aborted (core dumped)
我正在使用popOS 22.04 LTS,我是c++和glfw的新手,请帮助我解决这个问题
问题
之所以会出现这些错误,是因为glfw框架在用于创建窗口之前没有机会进行初始化。因此,glfw将返回给定的错误消息。
Wayland: Failed to connect to display
The GLFW library is not initialized
main: ./src/posix_thread.c:64: _glfwPlatformGetTls: Assertion `tls-posix.allocated == GLFW_TRUE' failed.
Aborted (core dumped)
解决方案
要解决此问题,请尝试移动代码段
if(!glfwInit()){
std::cout << "Failed to initialize GLFW!" << std::endl;
return -1;
}
在主函数开头的GLFWwindow* window
声明之上。
快速提示
尝试在一行中声明并初始化窗口,如下所示:GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "GLFW WINDOW", NULL, NULL)
它更容易阅读,总体上有助于减少代码行数。