I decided to port one of my simple for-learning-purposes OpenGL applications over to SDL2 from GLFW last night. I ran in to a few problems along the way, I’ll share my solutions with you here. The main problem was that SDL2 doesn’t handle extension loading for you like GLFW does. Easy enough to solve, just use GLEW right? Well yes, but the caveat here isn’t so obvious.

Without GLEW my program compiled but returned a bunch of warnings about “implicit declaration of function ‘glClear'” and so forth, for all OpenGL functions. This is to be expected, given that you need to manually load OpenGL functions when using SDL2.

After inserting the GLEW header and glewInit() my program compiled just fine, but gave a segfault as soon as it tried to compile one of my shaders. The error string returned with glewGetErrorString() was “Missing GL Version”, not exactly helpful. The solution to my particular problem was in my placement of glewInit(). This function MUST be run AFTER the following have been completed:

1. Creating a window with the SDL_WINDOW_OPENGL flag.
2. Creating a valid OpenGL context with SDL_GL_CreateContext()
3. Setting the newly created context as current with SDL_GL_MakeCurrent()

It was that third step that threw me off, but after moving things around my program was able to compile and run properly.

I came across a few other useful tidbits that may help others in similar situations. The “Missing GL Version” is returned for a number of different reasons. A common cause is that GLEW was not configured to make use of features in OpenGL versions greater than 2.0. By default, GLEW is only configured to make use of features available in OpenGL 2.0 and lower. The solution to this is adding the following line before glewInit():

glewExperimental = GL_TRUE;

Additionally, you can explicitly tell SDL2 which version of OpenGL you want to target with the following lines. In my case, version 3.3:

SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);

You can download the source code for my OpenGL with SDL2 sample program here. It draws a triangle with red, green, and blue corners. Quit by pressing the escape key.