Getting started with SDL2 with C++

Let's setup SDL2 Development environment.

  • First download and install IDE clion here this IDE will save a lot of time for us.
  • And the download SDL2 development bundle here
  • Extract the sdl library to your favourite path for me its on C:/tools/SDL2

Then let's setup the project.

  • Open CLion, and then new project give it name MyApp
  • Choose C++ Executable
  • And then config the CMAKELists, add sdl library to it
cmake_minimum_required(VERSION 3.17)
project(MyApp)

set(CMAKE_CXX_STANDARD 14)

include_directories(C:/tools/SDL2/include)
link_directories(C:/tools/SDL2/lib/x64)

add_executable(MyApp main.cpp)

target_link_libraries(${PROJECT_NAME} SDL2 SDL2main)
  • Then add this simple window apps on main.cpp
#include <iostream>
#define SDL_MAIN_HANDLED
#include <SDL.h>

const int SCREEN_WIDTH = 1080;
const int SCREEN_HEIGHT = 768;

int main(int argc, char *args[]) {
    SDL_Window *window = NULL;
    SDL_Surface *surface = NULL;
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        std::cout << "SDL cannot be initialed: " << SDL_GetError() << std::endl;
    } else {
        window = SDL_CreateWindow(
                "SDL Lesson1",
                SDL_WINDOWPOS_UNDEFINED,
                SDL_WINDOWPOS_UNDEFINED,
                SCREEN_WIDTH,
                SCREEN_HEIGHT,
                SDL_WINDOW_SHOWN
        );
    }

    if (window == NULL) {
        std::cout << "SDL cannot create window: " << SDL_GetError() << std::endl;
    } else {
        surface = SDL_GetWindowSurface(window);
        SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 0, 0));
        SDL_UpdateWindowSurface(window);

        // SDL_Delay() will not draw the window properly
        bool loop = true;
        while (loop) {
            SDL_Event e;
            while (SDL_PollEvent(&e)) {
                if (e.type == SDL_QUIT) {
                    loop = false;
                }
            }
        }
    }
}
  • And run the program, you should see simple window with red background.