glGenVertexArrays 导致分段错误,如何正确设置 OpenGL 上下文?

glGenVertexArrays causes a segmentation fault, how do I properly set up an OpenGL context?

我正在尝试编写一个简单的三角形代码。但是 glGenVertexArrays(1, &VertexArrayID) 每当我 运行 它时都会导致分段错误。

SDL_Init(SDL_INIT_VIDEO);

SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);

SDL_Window* window = SDL_CreateWindow("OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL);
SDL_GLContext context = SDL_GL_CreateContext(window);

SDL_Event event;
SDL_bool quit = SDL_FALSE;

GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID); // This causes crash

我在这里发现了完全相同的东西 OpenGL Segfaults on glGenVertexArrays 但是

I forgot to setup an OpenGL context. All fixed now.

没有帮助,因为我相信我已经创建了一个 OpenGL 上下文 SDL_GLContext context = SDL_GL_CreateContext(window);

如何正确设置 OpenGL 上下文?

你必须Initialize GLEW。创建 OpenGL 上下文后立即调用 glewInit

SDL_GLContext context = SDL_GL_CreateContext(window);

if (glewInit() != GLEW_OK)
{
    // error handling
    // [...]
}

请注意,glewInit will return GLEW_OK f it was successful. glewInit 初始化 OpenGL 函数的函数指针。如果您尝试通过未初始化的函数指针调用该函数,则会发生分段错误。