Initializing SDL

SDL is composed of eight subsystems - Audio, CDROM, Event Handling, File I/O, Joystick Handling, Threading, Timers and Video. Before you can use any of these subsystems they must be initialized by calling SDL_Init (or SDL_InitSubSystem). SDL_Init must be called before any other SDL function. It automatically initializes the Event Handling, File I/O and Threading subsystems and it takes a parameter specifying which other subsystems to initialize. So, to initialize the default subsystems and the Video subsystems you would call:

    SDL_Init ( SDL_INIT_VIDEO );

To initialize the default subsystems, the Video subsystem and the Timers subsystem you would call:


SDL_Init is complemented by SDL_Quit (and SDL_QuitSubSystem). SDL_Quit shuts down all subsystems, including the default ones. It should always be called before a SDL application exits.

With SDL_Init and SDL_Quit firmly embedded in your programmers toolkit you can write your first and most basic SDL application. However, we must be prepared to handle errors. Many SDL functions return a value and indicates whether the function has succeeded or failed, SDL_Init, for instance, returns -1 if it could not initialize a subsystem. SDL provides a useful facility that allows you to determine exactly what the problem was -- every time an error occurs within SDL, an error message is stored, which can be retrieved using SDL_GetError. Use this often, because you can never know too much about an error.

Example: Initializing SDL

#include "SDL.h"   /* All SDL apps need this */
#include <stdio.h>
#include <stdlib.h> /* for exit() */

int main(int argc, char** argv) {
    printf("Initializing SDL.\n");
    /* Initialize defaults, Video and Audio subsystems */
    if((SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)==-1)) { 
        printf("Could not initialize SDL: %s.\n", SDL_GetError());

    printf("SDL initialized.\n");

    printf("Quitting SDL.\n");
    /* Shutdown all subsystems */


Compiling the application

The program can be compiled by:

In linux:

 gcc -o <output> <source_file.c> `sdl-config --cflags --libs`

Initializing_SDL (last edited 2009-05-15 18:05:06 by yix)