Skip to content
systemcoding.dev
GPU

The Complete Guide to Windowing and Input With GLFW and SDL

Open windows, read keyboard, mouse and gamepad input, handle resizes and high-DPI, and choose between GLFW 3.4 and SDL 3.2 for OpenGL and Vulkan programs.

30 min read
Summarize in AI
Flat illustration of a GPU die of compute units with one thread block lit, with the C, NVIDIA and Khronos Group logos.

Before a graphics program draws anything, something has to ask the operating system for a window, hand the GPU a surface to present to, and deliver the keystrokes, mouse motion and controller input that arrive while the program runs. Each platform does this differently: Win32 on Windows, Cocoa on macOS, X11 or Wayland on Linux. A windowing library hides those differences behind one API, and two libraries cover almost every cross-platform renderer written in C or C++: GLFW and SDL. This guide teaches both from the first window to a complete input layer, using GLFW 3.4 and SDL 3.2 with C11, and it ends with a decision table so you can pick one for a new project. The GPU topic of this site continues from here into shaders and Vulkan, and everything on those pages assumes a window exists.

What a windowing library does and does not do

A windowing library does four jobs. It creates and manages windows, including size, title, fullscreen and the cursor. It creates a graphics context or a surface that OpenGL or Vulkan can render into. It collects input events from the operating system and delivers them in a uniform form. And it reports monitors, video modes and content scale.

It does not draw. GLFW and SDL do not provide a renderer for OpenGL or Vulkan; they hand you the context or the surface and step aside. SDL has its own 2D renderer and, in version 3, a GPU API that targets Vulkan, Metal and Direct3D 12, and those are separate subsystems you can ignore. It does not load OpenGL functions: on Windows and Linux the driver exports only old OpenGL entry points, so a loader such as glad reads the rest at run time through a function the windowing library provides, glfwGetProcAddress or SDL_GL_GetProcAddress. And it does not manage a game loop, timing or threads for you, although it supplies the clock and the swap-interval control the loop needs.

GLFW and SDL at a glance

GLFW is small. Its scope is windows, contexts, surfaces, monitors, keyboard, mouse, gamepads and the clipboard, and it stays inside that scope on purpose. It ships as one library with a C API, and its documentation is a manual of a few hundred pages. Version 3.4 added a runtime choice of platform on Linux, so one binary can pick Wayland or X11, plus a native Wayland path, a native X11 path and Windows, macOS and several BSD backends.

SDL, the Simple DirectMedia Layer, is wide. Version 3, whose first stable release is 3.2, is a rewrite of the SDL2 API that adds a consistent naming scheme, bool returns, a GPU API and many fixes, and it covers window and input work plus audio, haptics, sensors, file dialogs, timers, threads and mobile platforms. It is the library behind many shipped games and emulators.

ConcernGLFW 3.4SDL 3.2
ScopeWindows, contexts, inputWindows, input, audio, timers, threads, GPU API, mobile
API styleCallbacks, plus pollingEvent queue, plus polling
Create a windowglfwCreateWindow(w, h, title, monitor, share)SDL_CreateWindow(title, w, h, flags)
OpenGL contextCreated with the windowSDL_GL_CreateContext(window)
Vulkan surfaceglfwCreateWindowSurfaceSDL_Vulkan_CreateSurface
GamepadsBuilt in, SDL-style mapping databaseFull gamepad API with rumble and sensors
Mobile and consolesNoiOS and Android supported
BuildOne small libraryLarger, many optional subsystems

The rest of the guide shows each task in both libraries side by side, so the differences are concrete.

Setting up a build

Both libraries are found by CMake. On a system where you installed them, find_package locates them, and FetchContent pulls them from source if you prefer to vendor them. This CMakeLists.txt builds a program against GLFW with glad, which you generate once from the glad2 generator for OpenGL 4.5 core and place under third_party/glad:

CMakeLists.txtcmake
cmake_minimum_required(VERSION 3.24)
project(window_demo C)

set(CMAKE_C_STANDARD 11)

find_package(glfw3 3.4 REQUIRED)
find_package(SDL3 3.2 REQUIRED)

add_library(glad third_party/glad/src/gl.c)
target_include_directories(glad PUBLIC third_party/glad/include)

add_executable(glfw_demo glfw_demo.c)
target_link_libraries(glfw_demo PRIVATE glfw glad)

add_executable(sdl_demo sdl_demo.c)
target_link_libraries(sdl_demo PRIVATE SDL3::SDL3 glad)

The imported targets carry include paths and link flags, so no manual flags are needed. On Linux you also need the development packages of your display server: on a Debian-style system libwayland-dev, libxkbcommon-dev and the X11 headers for GLFW's X11 backend. The manual of each library lists the exact packages for your distribution.

The smallest GLFW program

The shortest complete GLFW program opens a window, clears it and closes on request. Read it for the order of the calls:

glfw_demo.cc
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#include <stdio.h>

static void on_error(int code, const char* description) {
    fprintf(stderr, "GLFW error %d: %s\n", code, description);
}

int main(void) {
    glfwSetErrorCallback(on_error);
    if (!glfwInit()) return 1;

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(960, 540, "GLFW window", NULL, NULL);
    if (!window) { glfwTerminate(); return 1; }

    glfwMakeContextCurrent(window);
    if (!gladLoadGL(glfwGetProcAddress)) { glfwTerminate(); return 1; }
    glfwSwapInterval(1);

    printf("GL_VERSION: %s\n", glGetString(GL_VERSION));

    while (!glfwWindowShouldClose(window)) {
        glClearColor(0.10f, 0.12f, 0.16f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}

The error callback comes first because GLFW reports failures only through it, and glfwInit and glfwCreateWindow return only a null or false result. The hints must be set before the window exists, since they describe the context to create. glfwMakeContextCurrent attaches the context to the calling thread, and only after that can glad load the entry points. glfwSwapInterval(1) waits for one vertical blank per swap, which is the default way to cap the frame rate at the display's refresh. The loop draws, swaps and then polls events, because glfwPollEvents is what makes the window respond to the operating system at all.

On a Linux machine with a Mesa driver, the printed line looks like this, and the exact text depends on the driver and version:

Text
GL_VERSION: 4.6 (Core Profile) Mesa 25.0.7

The smallest SDL program

The SDL3 version has the same shape, with a different vocabulary. SDL3 returns bool from most functions, where true means success, and reports the reason through SDL_GetError():

sdl_demo.cc
#include <glad/gl.h>
#include <SDL3/SDL.h>
#include <stdio.h>

int main(void) {
    if (!SDL_Init(SDL_INIT_VIDEO)) {
        fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
        return 1;
    }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

    SDL_Window* window = SDL_CreateWindow("SDL window", 960, 540, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
    if (!window) {
        fprintf(stderr, "SDL_CreateWindow failed: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    SDL_GLContext gl = SDL_GL_CreateContext(window);
    if (!gl) { SDL_DestroyWindow(window); SDL_Quit(); return 1; }
    if (!gladLoadGL((GLADloadfunc)SDL_GL_GetProcAddress)) return 1;
    SDL_GL_SetSwapInterval(1);

    printf("GL_VERSION: %s\n", glGetString(GL_VERSION));

    bool running = true;
    while (running) {
        SDL_Event e;
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_EVENT_QUIT) running = false;
        }
        glClearColor(0.10f, 0.12f, 0.16f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        SDL_GL_SwapWindow(window);
    }

    SDL_GL_DestroyContext(gl);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

Differences worth noticing at once. SDL attributes are set before window creation like GLFW hints, but the context is created in a separate call on the window. The window takes its flags as a bitmask, and in SDL3 the signature is SDL_CreateWindow(title, w, h, flags) with no position arguments, which is a change from SDL2. Closing the window arrives as an event of type SDL_EVENT_QUIT that you must handle, where GLFW sets a flag you test. And SDL3 renamed the context destructor to SDL_GL_DestroyContext, so SDL2 code that calls SDL_GL_DeleteContext needs an update.

Two event models

The central design difference is how input reaches your code. GLFW is callback-first. You register a function for each kind of event, and glfwPollEvents calls them from inside the poll, on the thread that called it. SDL is queue-first. The library fills an event queue, and you drain it with SDL_PollEvent in a loop and switch on the event type.

Neither model is better. Callbacks suit code that wants to react at the moment of the event and keep state in a user pointer. A queue suits code that wants to process all input of a frame in one place, in order, and perhaps record it. Both libraries also support polling the current state, glfwGetKey and SDL_GetKeyboardState, which is the natural way to read held keys during movement.

glfw_callbacks.cc
typedef struct {
    int width, height;
    bool wireframe;
} App;

static void on_key(GLFWwindow* w, int key, int scancode, int action, int mods) {
    App* app = glfwGetWindowUserPointer(w);
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(w, GLFW_TRUE);
    if (key == GLFW_KEY_F1 && action == GLFW_PRESS)
        app->wireframe = !app->wireframe;
}

// after creating the window:
// App app = {960, 540, false};
// glfwSetWindowUserPointer(window, &app);
// glfwSetKeyCallback(window, on_key);

A GLFW callback is a plain C function pointer with no closure, so state travels through glfwSetWindowUserPointer. Pass a pointer to a struct that outlives the window, and read it back with glfwGetWindowUserPointer inside the callback. A global variable works for a toy program and breaks the moment you open a second window.

Keyboard: keys, scancodes and text

Keyboard input has three levels, and mixing them up is the most common source of "works on my machine" bugs.

A key code names the key by the symbol the current layout assigns to it. GLFW_KEY_W and SDLK_W mean "the key labeled W" and move on a French AZERTY layout, where that label sits where QWERTY has Z. A scancode names the physical position, independent of the layout. And text input delivers the characters the user actually composed, after layout, modifiers and input methods are applied.

Use each for what it is for. Movement keys such as WASD belong to the physical position, so use scancodes: on any layout the four keys under the left hand form the same diamond. Shortcuts that the user thinks of by letter, such as Ctrl+S, belong to key codes. Text boxes belong to text input.

In GLFW the key callback receives both a key and a scancode, and text arrives in a separate character callback:

glfw_text.cc
static void on_char(GLFWwindow* w, unsigned int codepoint) {
    printf("typed U+%04X\n", codepoint);
}

// glfwSetCharCallback(window, on_char);

If the user presses Shift and the A key on a US layout, the character callback receives the Unicode code point 65:

Text
typed U+0041

SDL3 separates the layers the same way, with a twist: text input is off by default on desktop platforms until you call SDL_StartTextInput(window). When it is on, the queue carries SDL_EVENT_TEXT_INPUT events with a UTF-8 string, and SDL_EVENT_KEY_DOWN events carry e.key.key for the key code, e.key.scancode for the position and e.key.repeat to separate the first press from auto-repeat:

sdl_keys.cc
case SDL_EVENT_KEY_DOWN:
    if (e.key.repeat) break;
    if (e.key.key == SDLK_ESCAPE) running = false;
    if (e.key.scancode == SDL_SCANCODE_W) move_forward = true;
    break;
case SDL_EVENT_KEY_UP:
    if (e.key.scancode == SDL_SCANCODE_W) move_forward = false;
    break;
case SDL_EVENT_TEXT_INPUT:
    printf("text: %s\n", e.text.text);
    break;

Pressing and releasing W on a US keyboard while text input is active produces:

Text
text: w

Note that the key-down for W triggers no print, since only the text event prints. Always start text input only while a text field has focus. On mobile platforms it raises the on-screen keyboard, and on desktop it enables the input method editor that composes Chinese, Japanese and Korean text.

Held keys and polling

Event-driven code toggles flags on press and release. Polling asks the library for the current state, which is simpler for continuous movement:

glfw_poll.cc
float speed = 3.0f * dt;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) pos_z -= speed;
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) pos_z += speed;
sdl_poll.cc
const bool* keys = SDL_GetKeyboardState(NULL);
float speed = 3.0f * dt;
if (keys[SDL_SCANCODE_W]) pos_z -= speed;
if (keys[SDL_SCANCODE_S]) pos_z += speed;

The SDL3 pointer is to a bool array indexed by scancode, which changed from Uint8 in SDL2. The array is owned by SDL, stays valid for the life of the program and updates when you pump events, so call it after the poll loop and never store the contents. GLFW's polling function has a documented catch: a key that is pressed and released between two polls can be missed, unless you enable the GLFW_STICKY_KEYS input mode, which keeps a pressed state until you read it once.

Mouse position, buttons and scroll

Mouse reading follows the same split. GLFW delivers glfwSetCursorPosCallback, glfwSetMouseButtonCallback and glfwSetScrollCallback, and its coordinates are in screen coordinates measured in points from the top-left corner of the window's content area. SDL3 posts SDL_EVENT_MOUSE_MOTION, SDL_EVENT_MOUSE_BUTTON_DOWN, SDL_EVENT_MOUSE_BUTTON_UP and SDL_EVENT_MOUSE_WHEEL, and in SDL3 the coordinates are floats, which matter on high-DPI displays where a point is not a pixel.

A 3D camera does not want the cursor position. It wants relative motion, and it wants the cursor hidden and confined so it cannot leave the window or hit a screen edge and stop. Both libraries have a mode for this:

glfw_mouse_look.cc
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
if (glfwRawMouseMotionSupported())
    glfwSetInputMode(window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);

static double last_x, last_y;
static bool first = true;
static void on_cursor(GLFWwindow* w, double x, double y) {
    if (first) { last_x = x; last_y = y; first = false; }
    yaw   += (float)(x - last_x) * 0.1f;
    pitch += (float)(last_y - y) * 0.1f;
    last_x = x; last_y = y;
}

GLFW_CURSOR_DISABLED hides the cursor and gives it unlimited virtual range, so the reported position keeps changing at the screen edge. Raw motion bypasses the operating system's pointer acceleration, which is what a camera needs, and glfwRawMouseMotionSupported checks the platform first because not every platform has it. The first flag exists because the first callback after disabling the cursor reports a position far from the previous one, and without it the camera jumps.

SDL3 puts this in one call, and gives relative motion directly with no subtraction:

sdl_mouse_look.cc
SDL_SetWindowRelativeMouseMode(window, true);

// in the event loop:
case SDL_EVENT_MOUSE_MOTION:
    yaw   += e.motion.xrel * 0.1f;
    pitch -= e.motion.yrel * 0.1f;
    break;

xrel and yrel are the motion since the previous event. In SDL3 relative mode takes the window as its argument and replaced the global SDL_SetRelativeMouseMode of SDL2. Turn it off when the game opens a menu, so the user gets the cursor back.

Window size, framebuffer size and scale

A window has more than one size, and confusing them produces the classic bug of a scene rendered into a quarter of the window on a Retina display. The window size is measured in screen coordinates, the units the operating system uses for layout. The framebuffer size is measured in pixels, the units the GPU renders in. On a platform with display scaling the two differ: a 960 by 540 window on a macOS display with a scale factor of 2 has a framebuffer of 1920 by 1080 pixels.

Always size the viewport from the framebuffer. In GLFW, query it and update on the framebuffer-size callback:

glfw_resize.cc
static void on_fb_size(GLFWwindow* w, int width, int height) {
    glViewport(0, 0, width, height);
}

// glfwSetFramebufferSizeCallback(window, on_fb_size);
// Call glViewport once at startup too, with glfwGetFramebufferSize.

SDL3 offers SDL_GetWindowSizeInPixels for the pixel size and posts SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED when it changes. To make the window itself high-DPI aware, create it with SDL_WINDOW_HIGH_PIXEL_DENSITY:

sdl_resize.cc
SDL_Window* window = SDL_CreateWindow("SDL window", 960, 540,
    SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY);

// in the event loop:
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
    glViewport(0, 0, e.window.data1, e.window.data2);
    break;

For SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED, the new size in pixels arrives in data1 and data2. Without the high-density flag, SDL gives you a framebuffer sized to the window, which looks blurry on a scaled display. With it, you get the sharp native resolution and must handle the size difference yourself, including scaling mouse coordinates by SDL_GetWindowPixelDensity.

GLFW 3.4 handles the Retina case through a window hint, GLFW_SCALE_FRAMEBUFFER, which on macOS and Wayland controls whether the framebuffer is scaled to the display's native resolution, and it is true by default. The related call glfwGetWindowContentScale returns the scale factors for drawing UI at a readable size.

A window being resized also stalls the loop on some platforms. On Windows and macOS, the operating system runs a modal loop while the user drags a window edge, and glfwPollEvents does not return until the drag ends, so the application stops rendering. The standard fix is to render from inside the refresh callback glfwSetWindowRefreshCallback, or to draw on a second thread, which the next section covers.

Fullscreen and monitors

A window becomes fullscreen when you tell the library which monitor it belongs to. GLFW uses glfwSetWindowMonitor, which switches in both directions and needs the windowed rectangle to go back to:

glfw_fullscreen.cc
static int saved_x, saved_y, saved_w, saved_h;

void toggle_fullscreen(GLFWwindow* window) {
    if (glfwGetWindowMonitor(window)) {
        glfwSetWindowMonitor(window, NULL, saved_x, saved_y, saved_w, saved_h, 0);
    } else {
        glfwGetWindowPos(window, &saved_x, &saved_y);
        glfwGetWindowSize(window, &saved_w, &saved_h);
        GLFWmonitor* m = glfwGetPrimaryMonitor();
        const GLFWvidmode* mode = glfwGetVideoMode(m);
        glfwSetWindowMonitor(window, m, 0, 0, mode->width, mode->height, mode->refreshRate);
    }
}

Passing the monitor's current video mode gives a fullscreen window at the desktop resolution with no mode switch, which is the form most modern games use. In SDL3, SDL_SetWindowFullscreen(window, true) does the same, and the window's fullscreen mode decides whether it switches display modes or uses a desktop-resolution borderless window. With no explicit mode set, SDL3 uses the borderless desktop form, which avoids the black flicker of a real mode change. Call SDL_SetWindowFullscreen(window, false) to return to windowed mode, and SDL remembers the earlier rectangle for you.

Gamepads

Controllers differ in button order and axis layout by vendor and by operating system, so both libraries map the raw device into a standard layout, an Xbox-style pad with two sticks, two triggers, a d-pad and face buttons. Both use the same community mapping database format, so a controller that works in one works in the other.

glfw_gamepad.cc
GLFWgamepadstate state;
if (glfwJoystickIsGamepad(GLFW_JOYSTICK_1) && glfwGetGamepadState(GLFW_JOYSTICK_1, &state)) {
    float lx = state.axes[GLFW_GAMEPAD_AXIS_LEFT_X];
    float ly = state.axes[GLFW_GAMEPAD_AXIS_LEFT_Y];
    if (state.buttons[GLFW_GAMEPAD_BUTTON_A] == GLFW_PRESS) jump();
    if (fabsf(lx) > 0.15f || fabsf(ly) > 0.15f) move(lx, ly);
}

GLFW polls. Axes are floats in -1 to 1 and buttons are GLFW_PRESS or GLFW_RELEASE. The dead zone check of 0.15 is yours to choose, since a resting analog stick never reports exactly zero. SDL3 is event-driven for connection, and polling for values:

sdl_gamepad.cc
SDL_InitSubSystem(SDL_INIT_GAMEPAD);

// in the event loop:
case SDL_EVENT_GAMEPAD_ADDED:
    pad = SDL_OpenGamepad(e.gdevice.which);
    break;
case SDL_EVENT_GAMEPAD_REMOVED:
    SDL_CloseGamepad(pad);
    pad = NULL;
    break;

// each frame:
if (pad) {
    float lx = SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTX) / 32767.0f;
    if (SDL_GetGamepadButton(pad, SDL_GAMEPAD_BUTTON_SOUTH)) jump();
}

Axis values come back as Sint16, so divide by 32767 for a float. SDL names face buttons by position, SOUTH, EAST, WEST and NORTH, instead of by label, so one binding works for Xbox, PlayStation and Nintendo layouts. A later post in this series covers the gamepad API in more detail.

Creating a Vulkan surface

For Vulkan the window needs no context. You create the window with no client API and ask the library for a VkSurfaceKHR on a VkInstance you made. In GLFW:

glfw_vulkan.cc
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow* window = glfwCreateWindow(960, 540, "Vulkan", NULL, NULL);

uint32_t count = 0;
const char** exts = glfwGetRequiredInstanceExtensions(&count);
// add exts to VkInstanceCreateInfo.ppEnabledExtensionNames, create the instance

VkSurfaceKHR surface;
if (glfwCreateWindowSurface(instance, window, NULL, &surface) != VK_SUCCESS) { /* fail */ }

SDL3 mirrors it with SDL_WINDOW_VULKAN, SDL_Vulkan_GetInstanceExtensions(&count) and SDL_Vulkan_CreateSurface(window, instance, NULL, &surface), which returns bool. The required extension names depend on the platform, which is the reason to ask the library instead of hard-coding VK_KHR_win32_surface. A dedicated post walks through the surface on each platform.

Timing and the loop

A loop that advances physics by "one step per frame" runs at different speeds on different displays. Scale motion by the frame time, and keep physics on a fixed step with an accumulator. Each library provides a high-resolution clock: glfwGetTime returns seconds as a double since init, and SDL_GetTicksNS returns nanoseconds since SDL initialized.

loop_timing.cc
double previous = glfwGetTime();
double accumulator = 0.0;
const double step = 1.0 / 60.0;

while (!glfwWindowShouldClose(window)) {
    double now = glfwGetTime();
    double frame = now - previous;
    previous = now;
    if (frame > 0.25) frame = 0.25;   // avoid a spiral after a long stall
    accumulator += frame;

    glfwPollEvents();
    while (accumulator >= step) {
        update(step);
        accumulator -= step;
    }
    render(accumulator / step);
    glfwSwapBuffers(window);
}

Clamping the frame time prevents a long stall, such as a dragged window, from queuing a burst of updates that make the next stall longer. The fraction passed to render is the interpolation factor between the last two physics states. Vertical sync via glfwSwapInterval(1) or SDL_GL_SetSwapInterval(1) paces the swap to the display.

Threads and the macOS main thread

Window and event functions belong to the main thread, and macOS enforces it: Cocoa requires event processing on the thread that started the process. GLFW states which of its functions may be called from any thread, and the rule of thumb is that only the context-current and buffer-swap functions may move. A common design keeps the main thread running the event loop and moves rendering to a worker that owns the context:

render_thread.cc
// main thread
glfwMakeContextCurrent(NULL);          // release the context here
start_render_thread(window);           // thread calls glfwMakeContextCurrent(window)
while (!glfwWindowShouldClose(window))
    glfwWaitEvents();                  // sleeps until something happens

A context is current on one thread at a time, so the main thread releases it before the worker takes it. glfwWaitEvents blocks until an event arrives instead of spinning, which keeps the main thread idle. A worker that needs the main thread to wake, for example to close the window, calls glfwPostEmptyEvent. SDL3 offers the same split with SDL_GL_MakeCurrent, and a later post works the macOS case through in full.

Linux: Wayland and X11

Linux has two display protocols, and GLFW 3.4 compiled with both backends picks one at startup. By default it prefers Wayland when a Wayland session is detected and falls back to X11. To force one, set the platform init hint before glfwInit:

glfw_platform.cc
glfwInitHint(GLFW_PLATFORM, GLFW_PLATFORM_X11);   // or GLFW_PLATFORM_WAYLAND
if (!glfwInit()) return 1;
printf("platform: %s\n", glfwGetPlatform() == GLFW_PLATFORM_WAYLAND ? "Wayland" : "X11");
Text
platform: X11

Wayland differs for applications in ways worth knowing: a client cannot position its own window or warp the cursor, and window decorations may be drawn by the client with a library instead of the compositor, so some GLFW calls report an error on Wayland where they work on X11. SDL3 picks a video driver through the SDL_VIDEO_DRIVER hint or environment variable, with wayland and x11 as the values.

Errors and diagnostics

Windowing failures are usually environment problems, and the libraries report them in different ways. GLFW sends them to the error callback you install first. SDL3 functions return false or null and set a message you read with SDL_GetError(). The messages you will see most often:

Text
GLFW error 65542: WGL: The driver does not appear to support OpenGL
GLFW error 65550: Failed to detect any supported platform

The first means a remote desktop or a basic video driver is in use. The second means no graphical session, such as an SSH shell, so run on the machine's own session or provide a display. A request for a version or profile the driver cannot give fails with a separate version-unavailable error, so lower the hint or check what the driver reports with glxinfo. SDL3 reports comparable text through SDL_GetError, for instance No available video device when it finds neither display server.

Build an input layer that does not know the library

Scattering glfwGetKey and SDL_GetKeyboardState calls through game code ties every file to one library and makes input impossible to test. The better structure is a small layer between the two: the windowing code translates raw events into an Input struct once per frame, and the rest of the program reads only that struct. The struct holds actions, not keys, so rebinding a key changes one table.

input.hc
#include <stdbool.h>

typedef enum { ACT_FORWARD, ACT_BACK, ACT_LEFT, ACT_RIGHT, ACT_JUMP, ACT_COUNT } Action;

typedef struct {
    bool  held[ACT_COUNT];      // down this frame
    bool  pressed[ACT_COUNT];   // went down this frame
    float look_dx, look_dy;     // relative mouse motion this frame
    float move_x, move_y;       // gamepad stick, -1..1
} Input;

void input_begin_frame(Input* in);                    // clears pressed[] and deltas
void input_set(Input* in, Action a, bool down);       // called by the backend
input.cc
#include "input.h"
#include <string.h>

void input_begin_frame(Input* in) {
    memset(in->pressed, 0, sizeof in->pressed);
    in->look_dx = in->look_dy = 0.0f;
}

void input_set(Input* in, Action a, bool down) {
    if (down && !in->held[a]) in->pressed[a] = true;
    in->held[a] = down;
}

The backend file then maps one library's events onto it. For GLFW, the key callback consults a table of scancode-to-action bindings:

glfw_input_backend.cc
#include <GLFW/glfw3.h>
#include "input.h"

typedef struct { int key; Action action; } Binding;

static const Binding bindings[] = {
    { GLFW_KEY_W, ACT_FORWARD }, { GLFW_KEY_S, ACT_BACK },
    { GLFW_KEY_A, ACT_LEFT },    { GLFW_KEY_D, ACT_RIGHT },
    { GLFW_KEY_SPACE, ACT_JUMP },
};

static void on_key(GLFWwindow* w, int key, int scancode, int act, int mods) {
    Input* in = glfwGetWindowUserPointer(w);
    if (act == GLFW_REPEAT) return;
    for (size_t i = 0; i < sizeof bindings / sizeof bindings[0]; ++i)
        if (bindings[i].key == key)
            input_set(in, bindings[i].action, act == GLFW_PRESS);
}

The pressed array is what makes one-shot actions such as jumping correct. A held flag fires on every frame the key stays down, and a jump bound to it would retrigger continuously, while pressed is true for exactly one frame. Resetting it at the start of each frame, before events are pumped, is the whole mechanism.

Because the game reads only Input, a unit test can fill the struct by hand and run the movement code with no window, no display and no library, which is how input logic gets covered by an automated test on a build server that has no screen.

input_test.cc
#include <assert.h>
#include "input.h"

int main(void) {
    Input in = {0};
    input_begin_frame(&in);
    input_set(&in, ACT_JUMP, true);
    assert(in.pressed[ACT_JUMP] && in.held[ACT_JUMP]);

    input_begin_frame(&in);
    input_set(&in, ACT_JUMP, true);          // still down, not a new press
    assert(!in.pressed[ACT_JUMP] && in.held[ACT_JUMP]);
    return 0;
}

The second assertion is the case the table-driven design protects: a key held across two frames produces one press and two held frames.

Block for events instead of spinning

The loops above run flat out and render a frame whenever they can. A tool, an editor or a viewer that only changes in response to input should sleep instead, because a window that redraws 200 times a second to show a static image wastes a laptop's battery. Both libraries can wait for an event.

GLFW provides glfwWaitEvents, which sleeps until at least one event arrives, and glfwWaitEventsTimeout(seconds) for a wake-up after a delay, which suits an animation that must continue on a timer:

glfw_wait.cc
while (!glfwWindowShouldClose(window)) {
    if (needs_redraw) {
        draw();
        glfwSwapBuffers(window);
        needs_redraw = false;
    }
    glfwWaitEventsTimeout(0.5);   // wake at least every half second
    needs_redraw = true;
}

SDL3 has SDL_WaitEvent(&e) and SDL_WaitEventTimeout(&e, ms), which return bool and fill the event on success. After a wait returns, drain the rest of the queue with SDL_PollEvent so one wake-up handles the whole burst, since events often arrive in groups such as a resize followed by an expose.

Another thread that needs the loop to wake, say a file loader that finished, calls glfwPostEmptyEvent or SDL_PushEvent with a user event type obtained from SDL_RegisterEvents. Both calls are documented as safe from any thread, which is what makes the pattern work.

The clipboard and dropped files

Both libraries expose the system clipboard as plain text, and both deliver dropped files as events. GLFW reads and writes with glfwGetClipboardString(NULL) and glfwSetClipboardString(NULL, text), and the string it returns is owned by GLFW and valid until the next clipboard call, so copy it if you need it longer. A drop arrives through glfwSetDropCallback, which receives an array of UTF-8 paths that is valid only during the callback:

glfw_drop.cc
static void on_drop(GLFWwindow* w, int count, const char** paths) {
    for (int i = 0; i < count; ++i)
        printf("dropped: %s\n", paths[i]);
}

// glfwSetDropCallback(window, on_drop);
Text
dropped: /home/user/models/crate.obj

SDL3 sends SDL_EVENT_DROP_FILE with the path in e.drop.data, wrapped by SDL_EVENT_DROP_BEGIN and SDL_EVENT_DROP_COMPLETE events when several files arrive together, and the clipboard functions are SDL_GetClipboardText and SDL_SetClipboardText. The text returned by SDL_GetClipboardText must be released with SDL_free, which is a frequent leak.

Window attributes and state

A window has properties you will adjust: title, icon, size limits, always-on-top and whether the user can resize it. GLFW sets most through hints before creation and functions afterwards:

glfw_attribs.cc
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
glfwWindowHint(GLFW_FOCUSED, GLFW_TRUE);
GLFWwindow* window = glfwCreateWindow(960, 540, "Viewer", NULL, NULL);

glfwSetWindowSizeLimits(window, 320, 200, GLFW_DONT_CARE, GLFW_DONT_CARE);
glfwSetWindowTitle(window, "Viewer - crate.obj");

The minimum size stops the user from dragging the window to a rectangle too small for your layout, and GLFW_DONT_CARE leaves a bound open. SDL3 uses SDL_SetWindowMinimumSize(window, 320, 200) and SDL_SetWindowTitle. Both libraries also report focus loss and minimization as events, which matter more than they look: a game that keeps rendering at full rate while minimized wastes power, and one that ignores focus loss leaves the user's movement keys stuck down when they switch applications. On focus loss, clear your held-key state by calling the input reset, and the stuck-key bug disappears.

focus.cc
static void on_focus(GLFWwindow* w, int focused) {
    Input* in = glfwGetWindowUserPointer(w);
    if (!focused) memset(in->held, 0, sizeof in->held);
}

Without that reset, a player who presses Alt+Tab while holding W returns to a character walking forward forever, because the key release went to the other application.

More than one window

Both libraries support several windows, and each has its own context, so you decide how to share GPU objects. GLFW takes a share argument to glfwCreateWindow, and contexts created with a shared window share textures, buffers and shaders but not vertex array objects or framebuffers, which are container objects in OpenGL. A tool with a main view and a floating preview window creates the second with the first as share, and the textures uploaded once appear in both. Callbacks are per window, so the user pointer pattern above gives each window its own state. Event polling is global, meaning one glfwPollEvents call services every window.

In SDL3, events carry a windowID field, and SDL_GetWindowFromID converts it back to the pointer. For OpenGL with several windows, create one context and make it current for whichever window is about to draw, using SDL_GL_MakeCurrent(window, gl), which is the usual pattern and avoids sharing rules entirely.

Common failures and what causes them

A table of the failures that account for most support questions saves time, because the symptom rarely names the cause.

SymptomCauseFix
Window opens, stays black or does not respondEvent loop never calls the poll functionCall glfwPollEvents or SDL_PollEvent every iteration
Scene fills a quarter of the window on a Retina displayViewport set from window sizeUse framebuffer or pixel size
glGetString(GL_VERSION) returns nullFunction used before the context is current or before loadingMake the context current, then run the loader
Camera snaps on the first mouse moveFirst cursor callback reports a large jumpInitialize the last position on the first event
Character walks forward after Alt+TabKey release delivered to another windowClear held state on focus loss
WASD wrong on French keyboardUsed key codes for movementUse scancodes
Crash on exit with a context errorDestroyed the window before the objects that use its contextDelete GL objects first, then window, then terminate
Frame rate stuck at 60Vsync enabledSet the swap interval to 0 to measure, then restore it

The exit-order row deserves a sentence. Every GL object lives in the context, and destroying the window destroys the context, so a destructor that calls glDeleteTextures afterwards has no current context and either fails or crashes. Release your own resources first.

Presentation: vsync, tearing and latency

The swap interval decides how the finished frame reaches the screen, and the choices trade smoothness against latency. An interval of 1 waits for the display's vertical blank before swapping, which removes tearing and caps the frame rate at the refresh rate. An interval of 0 swaps immediately, which gives the lowest latency and shows tearing whenever the swap lands mid-scan. A negative interval requests adaptive vsync where the driver supports the EXT_swap_control_tear extension: it waits for the blank when the frame is on time and swaps late frames immediately instead of dropping to half the refresh rate.

swap_interval.cc
// GLFW
glfwSwapInterval(-1);          // adaptive, if supported
// SDL3: returns false if the request is not supported
if (!SDL_GL_SetSwapInterval(-1)) SDL_GL_SetSwapInterval(1);

Adaptive vsync is a request, not a guarantee, and a driver that lacks the extension ignores or rejects it. GLFW documents that an unsupported negative value is not an error you can detect reliably, while SDL3 reports it through the return value, so the fallback line above works only with SDL. For Vulkan none of this applies: presentation is controlled by the present mode of the swapchain, FIFO for vsync, MAILBOX for low-latency triple buffering and IMMEDIATE for tearing, and the windowing library has no say in it.

Latency comes from the whole queue between input and display, not only the swap. Polling input as late as possible in the frame, right before building the frame's state, makes the picture reflect the most recent keystroke. Calling glfwPollEvents at the top of the loop and then doing a long update before rendering delays that picture by the update time. If you must choose, poll, update, render, swap in that order, and keep the update short.

A worked example: an orbit camera viewer

Putting the pieces together, the program below opens a resizable high-DPI window with GLFW, tracks the framebuffer size, orbits a camera while the left button is held and zooms with the scroll wheel. It draws nothing, because the point is the input path. It prints the camera state each time the user releases the mouse, so the result is checkable.

orbit.cc
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#include <stdio.h>

typedef struct {
    float yaw, pitch, distance;
    bool  dragging;
    double last_x, last_y;
} Camera;

static void on_button(GLFWwindow* w, int button, int action, int mods) {
    Camera* cam = glfwGetWindowUserPointer(w);
    if (button != GLFW_MOUSE_BUTTON_LEFT) return;
    if (action == GLFW_PRESS) {
        cam->dragging = true;
        glfwGetCursorPos(w, &cam->last_x, &cam->last_y);
    } else {
        cam->dragging = false;
        printf("yaw=%.1f pitch=%.1f distance=%.1f\n", cam->yaw, cam->pitch, cam->distance);
    }
}

static void on_cursor(GLFWwindow* w, double x, double y) {
    Camera* cam = glfwGetWindowUserPointer(w);
    if (!cam->dragging) return;
    cam->yaw   += (float)(x - cam->last_x) * 0.4f;
    cam->pitch += (float)(y - cam->last_y) * 0.4f;
    if (cam->pitch >  89.0f) cam->pitch =  89.0f;
    if (cam->pitch < -89.0f) cam->pitch = -89.0f;
    cam->last_x = x;
    cam->last_y = y;
}

static void on_scroll(GLFWwindow* w, double dx, double dy) {
    Camera* cam = glfwGetWindowUserPointer(w);
    cam->distance -= (float)dy * 0.5f;
    if (cam->distance < 1.0f) cam->distance = 1.0f;
}

static void on_fb_size(GLFWwindow* w, int width, int height) {
    glViewport(0, 0, width, height);
}

int main(void) {
    if (!glfwInit()) return 1;
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    GLFWwindow* window = glfwCreateWindow(960, 540, "Orbit", NULL, NULL);
    if (!window) { glfwTerminate(); return 1; }
    glfwMakeContextCurrent(window);
    gladLoadGL(glfwGetProcAddress);
    glfwSwapInterval(1);

    Camera cam = { 20.0f, 15.0f, 5.0f, false, 0.0, 0.0 };
    glfwSetWindowUserPointer(window, &cam);
    glfwSetMouseButtonCallback(window, on_button);
    glfwSetCursorPosCallback(window, on_cursor);
    glfwSetScrollCallback(window, on_scroll);
    glfwSetFramebufferSizeCallback(window, on_fb_size);

    int fw, fh;
    glfwGetFramebufferSize(window, &fw, &fh);
    glViewport(0, 0, fw, fh);

    while (!glfwWindowShouldClose(window)) {
        glClearColor(0.08f, 0.09f, 0.12f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(window);
        glfwWaitEventsTimeout(1.0 / 60.0);
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}

Suppose the user presses the left button, drags 50 pixels to the right and 10 pixels down, releases, and then scrolls the wheel up two notches and drags again with no motion. The first release reports the camera after the drag: yaw 20 plus 50 times 0.4, and pitch 15 plus 10 times 0.4.

Text
yaw=40.0 pitch=19.0 distance=5.0

After two notches of scroll up the distance falls by 1.0, so a second press and release with no motion prints:

Text
yaw=40.0 pitch=19.0 distance=4.0

Two choices in the program carry general lessons. The drag state lives in the camera struct reached through the user pointer, so no globals exist. And the loop uses glfwWaitEventsTimeout at roughly 60 Hz instead of a bare poll, which keeps the program responsive while leaving the CPU idle between frames.

Shutting down in the right order

Every program in this guide ends with the same three steps, and their order is not decoration. First release every object you created in the graphics API, because textures, buffers and programs belong to the context. Then destroy the window, which destroys the context with it. Last, terminate the library: glfwTerminate closes any windows still open and frees the library's state, and SDL_Quit shuts down every initialized subsystem.

A program that exits by calling exit from deep inside a callback skips this path, and on most desktops the operating system reclaims the memory anyway. That is acceptable for a throwaway tool and wrong for anything that holds a file, a network socket or a GPU capture. The dependable pattern is to set the close flag, let the loop finish its iteration and run the cleanup block at the bottom of main, so a single exit path handles every case.

Which library to choose

Pick GLFW when your project is a desktop renderer, a tool or a learning exercise, and you want the smallest dependency whose API fits on a page. It is the usual choice for graphics tutorials and for engines whose audio, networking and threading come from other libraries. Pick SDL when you need more than windows: audio, a gamepad API with rumble and sensors, file dialogs, mobile or console targets, or the GPU API. SDL's size is the cost, and you can build it with the subsystems you do not use turned off.

Neither library is a trap. The code in this guide that touches the graphics API is identical in both, and the layer between your game and the window is a few hundred lines, so a project can start on either and change later. A separate comparison of GLFW and SDL3 for a new renderer works through the decision with a table, and a migration post covers moving from SDL2 to SDL3.

What the guide does not cover

This guide treats the desktop. It does not cover the SDL mobile lifecycle, where an application can be suspended without warning and must release GPU resources, or web builds through Emscripten, where the loop is driven by the browser instead of your own while. It does not teach OpenGL or Vulkan themselves, and it does not cover UI toolkits. If your program is a document editor or a settings dialog, a GUI toolkit such as Qt gives you real controls, and a windowing library gives you a canvas and nothing else.

The behavior described here comes from the GLFW documentation and the SDL3 wiki.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.