无法在C ++中创建GLFWwindow - glfwCreateWindow返回nullptr?

时间:2016-02-27 23:24:13

标签: c++ visual-studio opengl glfw glew

在对代码运行多次测试之后,我确定GLFW和GLEW都已成功初始化,但当我尝试创建一个与{GLFW函数一起使用的GLFWwindow*对象时,glfwCreateWindow()函数返回一个nullptr。为什么这样,我该如何解决?这是我的代码:

#include <iostream>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

const GLuint windowWidth = 500, windowHeight = 500;

int main()
{
    glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(windowWidth, windowHeight, "Learn OpenGL", nullptr, nullptr);
    if (window == nullptr) {
        std::cout << "Failed to create GLFW window!" << std::endl;
        char myvar1; std::cin >> myvar1;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    if (glewInit() != GL_TRUE) {
        std::cout << "Failed to initialize GLEW" << std::endl;
        char myvar2; std::cin >> myvar2;
        return -1;
    }

    glViewport(0, 0, windowWidth, windowHeight);
    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glfwSwapBuffers(window);
    }

    glfwTerminate();

    return 0;
}

1 个答案:

答案 0 :(得分:3)

这可能是因为您为上下文创建指定了版本3.3,并且您的opengl版本低于3.3。

OpenGL:GLFW_CONTEXT_VERSION_MAJOR和GLFW_CONTEXT_VERSION_MINOR不是硬约束,但如果创建的上下文的OpenGL版本小于请求的上下文,则创建将失败。

如果您使用的是具有2个GPU的笔记本电脑,则可能会发生这种情况。他们出于功耗原因这样做,大多数应用程序将使用标准GPU运行,而对于游戏,例如它将使用高性能的。

例如我的笔记本电脑内置Intel(R)HD Graphics 3000(3.1 opengl版本)GPU和NVIDIA geforce gt 630M(4.4 opengl版本)GPU。

如果您右键单击应用程序快捷方式并且选择&#34;运行图形处理器&#34;: - &#34;高性能(NVIDIA)处理器&#34>,您可以查看您的笔记本电脑是否具有此功能。 - &#34;集成显卡(默认)&#34;

问题在于编辑器(eclipse / ms visual studio等)(在其中运行代码)将使用默认编辑器,并且通常具有比其他GPU低得多的opengl版本。

您可以通过始终使用高性能GPU运行编辑器程序来解决此问题。

如果您不使用笔记本电脑或只有一个GPU,请尝试更新您的驱动程序。

相关问题