This is a simple example that shows a basic SDL2 example. It is assumed that you have experience with C or C++ in this guide. I will be writing in C because SDL2 is written in C, and I think it makes for a simpler code to not mix lanaguages.

Installing SDL2

The process of installing SDL is a bit different depending on your operating system and development environment. I will show the easiest methods for some operatings systems.

Simple Example

Let’s dive into a simple SDL2 example to get a feel for how to set up and use SDL2 in a basic program. This code initializes SDL2 and then quits without doing much else. It’s a good starting point to ensure your SDL2 setup is working correctly.

#include <SDL2/SDL.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
    // Initialize SDL2 with video and audio subsystems
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) {
        fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError());
        return 1;
    }

    // Your SDL2 code goes here

    // Clean up and quit SDL2
    SDL_Quit();

    return 0;
}

Explanation

  1. Including SDL2 Headers: We include the SDL2 header file <SDL2/SDL.h>. This provides us with access to SDL2’s functions and definitions. We also include standard headers for input/output and string manipulation.

  2. Initializing SDL2: SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) initializes SDL2 with support for both video and audio. If initialization fails, it returns a non-zero value, and we print an error message using SDL_GetError().

  3. Quitting SDL2: SDL_Quit() cleans up and shuts down the SDL2 library. It’s important to call this function to release resources allocated by SDL2.