← Back to C++ Course | Chapter 18: Graphics | Lesson 7 of 7

C++ SDL2 with C++

What is SDL2?

SDL2 (Simple DirectMedia Layer) is a cross-platform library giving low-level, direct access to a machine's graphics hardware, keyboard, mouse, and audio devices, making it a common choice underneath both games and emulators. On Ubuntu, install it with sudo apt-get install libsdl2-dev.

Example: What is SDL2?

cpp
#include <SDL2/SDL.h>

int main() {
	SDL_Init(SDL_INIT_VIDEO); // low-level access to graphics/input/audio
	SDL_Quit();
	return 0;
}

Creating an SDL2 Window

SDL_CreateWindow() opens an actual OS-level window with a given title, position, and size, returning a handle you use for all further drawing into it. Every window you create must eventually be released with SDL_DestroyWindow() when your program exits, or the OS resource stays allocated.

Example: Creating an SDL2 Window

cpp
#include <SDL2/SDL.h>

int main() {
	SDL_Init(SDL_INIT_VIDEO);
	SDL_Window* window = SDL_CreateWindow("My Window", 0, 0, 800, 600, 0);
	SDL_DestroyWindow(window);
	SDL_Quit();
	return 0;
}

Rendering basic Shapes in SDL2

Drawing in SDL2 goes through an SDL_Renderer object attached to your window, rather than drawing to the window directly. SDL_RenderFillRect() draws a solid, color-filled rectangle at a given position and size using that renderer.

Example: Rendering basic Shapes in SDL2

cpp
#include <SDL2/SDL.h>

int main() {
	SDL_Window* window = SDL_CreateWindow("Shapes", 0, 0, 800, 600, 0);
	SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
	SDL_Rect rect = {50, 50, 120, 80};
	SDL_RenderFillRect(renderer, &rect);
	return 0;
}

Event Handling

SDL_PollEvent(), called in a loop, drains the queue of everything the OS has reported since the last check -- key presses, mouse movement, window-close requests -- letting your program branch on each event type and respond accordingly.

Example: Event Handling

cpp
#include <SDL2/SDL.h>

int main() {
	SDL_Event event;
	bool running = true;
	while (running && SDL_PollEvent(&event)) {
		if (event.type == SDL_QUIT)
			running = false;
	}
	return 0;
}

Clearing and Presenting

SDL_RenderClear() wipes the renderer's buffer back to a blank state before you draw the next frame's contents, and SDL_RenderPresent() then flips that finished buffer onto the actual screen -- without calling present, none of your drawing would ever become visible.

Example: Clearing and Presenting

cpp
#include <SDL2/SDL.h>

int main() {
	SDL_Window* window = SDL_CreateWindow("Present", 0, 0, 800, 600, 0);
	SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
	SDL_RenderClear(renderer);
	SDL_RenderPresent(renderer); // flips the buffer onto the screen
	return 0;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.