SDL (Simple DirectMedia Layer) - Getting started
In this section, we will show you how to initialise and shutdown SDL subsystems.
#include <stdio.h> /* printf and fprintf */
#ifdef _WIN32
#include <SDL/SDL.h> /* Windows-specific SDL2 library */
#else
#include <SDL2/SDL.h> /* macOS- and GNU/Linux-specific */
#endif
int main (int argc, char **argv)
{
/*
* Initialises the SDL video subsystem (as well as the events subsystem).
* Returns 0 on success or a negative error code on failure using SDL_GetError().
*/
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
fprintf(stderr, "SDL failed to initialise: %s\n", SDL_GetError());
return 1;
}
printf("SDL initialised!");
/* Shuts down all SDL subsystems */
SDL_Quit();
return 0;
}
You can download the source code of this section in this GitLab repository. All source code is stored in this group.
Linking SDL2 libraries edit
The basic functions required for SDL2 is either in the <SDL/SDL.h>
library or <SDL2/SDL.h>
library depending on the operating system, hence the above source code uses
#ifdef _WIN32
#include <SDL/SDL.h> /* Windows-specific SDL2 library */
#else
#include <SDL2/SDL.h> /* macOS- and GNU/Linux-specific */
#endif
main
macro in Windows
edit
When writing code for Windows machines, it is necessary to include
int main (int argc, char **argv)
since SDL overwrites the main
macro. According to SDL's FAQWindows:
You should be usingmain()
instead ofWinMain()
even though you are creating a Windows application, because SDL provides a version ofWinMain()
which performs some SDL initialization before calling your main code. If for some reason you need to useWinMain()
, take a look at the SDL source code insrc/main/win32/SDL_main.c
to see what kind of initialization you need to do in yourWinMain()
function so that SDL works properly.
Initialising SDL subsystems edit
When using a SDL subsystem, you must always initialise it first. In the following if-statement, we initialise the SDL video subsystem with the flag SDL_INIT_VIDEO
. If it succeeds, it returns 0
, otherwise it returns a negative error code and will print information about the error using SDL_GetError through the stderr
stream.
/*
* Initialises the SDL video subsystem (as well as the events subsystem).
* Returns 0 on success or a negative error code on failure using SDL_GetError().
*/
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
fprintf(stderr, "SDL failed to initialise: %s\n", SDL_GetError());
return 1;
}
You can initialise multiple subsystems using the |
operator:
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0)
{
fprintf(stderr, "SDL failed to initialise: %s\n", SDL_GetError());
return 1;
}
All information about the SDL_Init
function subsystems, and their flags can be found in the SDL Wiki's SDL_Init page.
Shutting down SDL subsystems edit
To shut down the SDL subsystems, you must execute
SDL_Quit();
However, this will only shut down the main subsystems; shutting down the TTF subsystem requires a different function
TTF_Quit();