opengl and SDL2 glgenbuffers segmentation fault

Viewed 151

I have a problem with opengl and SDL2. When I want to trigger glGenBuffers, the application crashes. Does anyone know where I made a mistake?

#define GLEW_STATIC
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <GL/glew.h>

using namespace std;

SDL_Window*win;
SDL_Event event;
const Uint8*keystate = SDL_GetKeyboardState(NULL);

SDL_GLContext context;

int main(int argc, char*args[])
{
    SDL_Init(SDL_INIT_EVERYTHING);
    glewExperimental = GL_TRUE;
    glewInit();
    win = SDL_CreateWindow("opengl",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,900,800,SDL_WINDOW_OPENGL);
    context = SDL_GL_CreateContext(win);
    SDL_GL_MakeCurrent(win,context);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
    glClearColor( 1.0, 1.0, 1.0, 1.0 );

    float positions[6] =
    {
        -0.5f,-0.5f,
        0.0f,0.5f,
        0.5f,0.0f
    };
    GLuint buffer;
    glGenBuffers(1,&buffer); //here
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glBufferData(GL_ARRAY_BUFFER, 6,positions,GL_STATIC_DRAW);

    while(true)
    {
        while(SDL_PollEvent(&event))
        {
            if(event.type==SDL_QUIT) return 0;
        }
        glClear(GL_COLOR_BUFFER_BIT);
        glDrawArrays(GL_TRIANGLES,0,3);
        SDL_GL_SwapWindow(win);
    }
}

I really don't know where the problem is, I would really be grateful to have someone help me.

1 Answers

he GLEW library has to be initialized, by glewInit, after the OpenGL context has become current by SDL_GL_MakeCurrent(win,context). See Initializing GLEW.

win = SDL_CreateWindow("opengl",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,
                       900,800,SDL_WINDOW_OPENGL);
context = SDL_GL_CreateContext(win);
SDL_GL_MakeCurrent(win,context);

if (glewInit() != GLEW_OK)
    return 0;

When you do it before, the initialization of glew fails and glewInit doesn't return GLEW_OK.

Related