当我开始时,我使用了 GLFW 示例代码:
#include <GLFW/glfw3.h>
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);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
运行此程序时,它会给我一个标题为“Hello world”的黑屏,这正是我想要的。但只需添加 GLAD:
#include <glad/glad.h>
#include <GLFW/glfw3.h>
...并给出窗口提示:
//Specify the OpenGL versions we're using
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
...它允许窗口初始化,但在调用 glClear(GL_COLOR_BUFFER_BIT)
时崩溃,并给出错误
'./Voxel\ Game' terminated by signal SIGSEGV (Address boundary error)
我知道这一点,因为当我删除该行时它可以工作,只是不会清除屏幕。
这是我现在拥有的完整代码,以防错误出现在其他地方:
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#define SCREEN_WIDTH 640
#define SCREEN_HIEGHT 480
int main()
{
GLFWwindow* window;
//Initialize the library
if (!glfwInit())
{
std::cout << "Failed to initalize GLFW" << std::endl;
return -1;
}
//Specify the OpenGL versions we're using
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
//Create a windowed mode window and its OpenGL context
window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HIEGHT, "Voxel Game", NULL, NULL);
if (!window)
{
std::cout << "Failed create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
//Make the window's context current
glfwMakeContextCurrent(window);
//Loop until the user closes the window
while (!glfwWindowShouldClose(window))
{
//Render here
//glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
//Swap front and back buffers
glfwSwapBuffers(window);
//Poll for and process events
glfwPollEvents();
}
glfwTerminate();
return 0;
}
最佳答案
您没有初始化 glad
,请在 glfwMakeContextCurrent()
之后添加 gladLoadGL(glfwGetProcAddress);
并检查它是否返回 OK。
一般来说,除了一些旧的 OpenGL1.1 东西(至少在 Windows 中)之外,没有 OpenGL 库,所有这些 GL 调用都是直接在图形驱动程序中实现的,GLAD 库只是定义了很多函数指针并包装了它们在更好的宏中。然后在初始化期间,它将动态加载机器上存在的驱动程序中的功能。因此需要为特定的 OpenGL 版本生成 GLAD。 因此,如果您在某些 GL 调用上遇到段错误,一个好的猜测是其中一些函数未找到,可能是因为它们在硬件上不受支持,或者因为您没有正确设置 GLAD/GLFW。
关于c++ - 当包含 GLAD 时,glClear() 会使 GLFW 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73357676/