Creating a Window Using SDL2

Matthew Clark
Nerd For Tech
Published in
4 min readJul 8, 2024

In my last article I set up SDL in visual studio. Now I am going to get a window to appear starting from the point where your project is already set up with a main C++ file.

We are first going to include the proper header files for the SDL libraries.

We are going to define two variables to determine the dimensions of the window we are going to create. we are also going to add the main function to the file.

Now create a new header file. At the top of the header file we are going to add a pragma once instruction to make sure this file is only included once in the project. We will also include the SDL libraries. Now create a class with public and private members. We are going to define three public functions to create the window, get the renderer, and free the resources we used and close SDL. We are also going to define a private SDL window and renderer.

Now create a new C++ file to implement this header. In the RenderWindow function we are going the create an SDL window using SDL_CreateWindow. The first parameter is going to be the title of the window, the next two are the position the window will be created at. The next two parameters are going to be the width and height of the window and the last parameter is the flag that makes the window show up. We will check to make sure the window was created properly.

We are going to do something similar with the renderer. The first parameter in this function is the window where the renderer is displayed, the next is the index of the rendering driver to initialize. We use -1 here to use the first one that is supported. The last parameter is a flag to tell the renderer how to work.

We also implement the functions to return the renderer and free up resources and quit SDL.

Back in main we are going to put it all together. Make sure to include the header file. We are going to initialize SDL and create the window and renderer.

Now we create the game loop. Start by creating a flag to determine if the game is running. Create and SDL_Event. We will use a while loop that is running while the game is running. We will also create an SDL_PollEvent and look for SDL_QUIT to end the loop. We will then set the color of the renderer and display it.

Once the game loop has ended we want to free resources and quit SDL.

Here are the complete C++ files.

This will create a window in SDL.

--

--