初始化时opengl分段错误

时间:2015-07-16 06:33:14

标签: opengl glfw

这是一个非常令人讨厌的问题,但每次程序试图运行'init()'时我都会遇到分段错误,我不明白为什么。我正在使用的库是:glew,glu,glfw3和来自这里的着色器加载器http://www.opengl-redbook.com/

#include <GL/glew.h>
#include <GL/glu.h>
#include <GLFW/glfw3.h>
#include <GL/gl.h>
#include "LoadShaders.h"
#include <iostream>
//g++ -c main.cpp -l glfw -l GLEW -l GL -l GLU -c LoadShaders.cpp 
//g++ -o run main.o LoadShaders.o -l GLEW -l glfw -l GL -l GLU

GLuint VAOs[1];
GLuint Buffers[1];
enum Attrib_IDs {vPosition = 0};
void init (void){

    glGenVertexArrays(1, VAOs);
    glBindVertexArray(VAOs[0]);

    GLfloat vertices[6][2] ={
        {-0.90, -0.90},
        {0.85, -0.90},
        {-0.90, 0.85},
        {0.90, -0.85},
        {0.90, 0.90},
        {-0.85, 0.90}
    };

    glGenBuffers(1, Buffers);
    glBindBuffer(GL_ARRAY_BUFFER, Buffers[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    ShaderInfo shaders[] = {
        {GL_VERTEX_SHADER, "game.vert"},
        {GL_FRAGMENT_SHADER, "game.frag"},
        {GL_NONE, NULL}
    };

    GLuint program = LoadShaders(shaders);
    glUseProgram(program);

    glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(vPosition);
}

int main(){
    GLFWwindow* window;

    /*initialize the glfw library*/
    if (!glfwInit())
    {
        return -1;
    }

    window = glfwCreateWindow(640, 480, "Hello world!", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);
    init();
    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {

        glClear(GL_COLOR_BUFFER_BIT);

        glBindVertexArray(VAOs[0]);
        glDrawArrays(GL_TRIANGLES, 0, 6);

        glFlush();
        /* Swap front and back buffers */
        glfwSwapBuffers(window);
        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;

}

1 个答案:

答案 0 :(得分:1)

结果我只是忘了使用glewInit()初始化glew。这样做之后一切运作良好