C++ SDL2 with C++
In this page:
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?
#include <SDL2/SDL.h>
int main() {
SDL_Init(SDL_INIT_VIDEO); // low-level access to graphics/input/audio
SDL_Quit();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: