Initializing SDL

SDL is composed of several subsystems; Timers, Video, Audio, Mice, Joysticks, Haptic (Force Feedback), Event Handling (including keyboards), File I/O and Multi-Threading. 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, Mice, File I/O and Multi-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 ( SDL_INIT_VIDEO | SDL_INIT_TIMER );

SDL_Init is complemented by SDL_Quit (and SDL_QuitSubSystem). SDL_Quit shuts down all subsystems. It should always be called before an 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

   1 #include "SDL.h"   /* All SDL apps need this */
   2 #include <stdio.h>
   3 #include <stdlib.h> /* for exit() */
   4 
   5 int main(int argc, char** argv) {
   6     
   7     printf("Initializing SDL.\n");
   8     
   9     /* Initialize defaults, Video and Audio subsystems */
  10     if((SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)==-1)) { 
  11         printf("Could not initialize SDL: %s.\n", SDL_GetError());
  12         exit(-1);
  13     }
  14 
  15     printf("SDL initialized.\n");
  16 
  17     printf("Quitting SDL.\n");
  18     
  19     /* Shutdown all subsystems */
  20     SDL_Quit();
  21     
  22     printf("Quitting...\n");
  23 
  24     exit(0);
  25 }

Compiling the application

The program can be compiled by:

In linux:

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

Or, using pkg-config:

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

See Also


CategorySDL13Tutorial

SDL-1.3/Initializing_SDL (last edited 2009-09-09 21:56:20 by d72-38-58-133)