Originally Published: Monday, 25 June 2001 Author: Josh Boudreau
Published to: develop_articles_tutorials/Development Tutorials Page: 2/4 - [Printable]

Programming Linux Games: An Introduction to SDL Development

Welcome to Game Week on Linux.com! All this week we'll be featuring and playing games. The game week feature article by Linux.com writer Josh "bitwize" Boudreau is a succinct introduction to programming with the SDL (Simple DirectMedia Layer) library, essential to understanding Linux game development. So all you game programmers or would be game programmers: read up!

Initializing SDL  << Page 2 of 4  >>

Initializing SDL

To use any of the SDL functions in your program you must first initialize the library with the SDL_Init() function. Depending on the features your application will use, you can decide to initialize all, or only certain subsystems of the SDL library. The SDL_Init() function takes a single argument which is a list of flags that can be bitwise or'd together to decide which subsystem to initialize. Here are the flags that can be passed to the SDL_Init function.

SDL_INIT_TIMER
SDL_INIT_AUDIO
SDL_INIT_VIDEO
SDL_INIT_CDROM
SDL_INIT_JOYSTICK
SDL_INIT_EVERYTHING
SDL_INIT_NOPARACHUTE
SDL_INIT_EVENTTHREAD

The names are pretty self-descriptive on what they initialize except for the SDL_INIT_NOPARACHUTE flag. When SDL_INIT_NOPARACHUTE is passed to SDL_Init(), SDL will provide a signal catcher, meaning that if your application segfaults SDL will clean up after itself. If we wanted to initialize SDL to use video and audio functions we could use the SDL_Init() function like this:

SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);

As you can see, each flag can be bitwise or'd together. SDL defines SDL_INIT_EVERYTHING to initialize all the subsystems of the library. Another useful function you can use to initialize SDL subsystems is the SDL_InitSubSystem() function. This function can be used, for example, if your application needs video and audio but joystick support is optional. Here's an example code snippet.

int main(int argc, char *argv[])
{
if( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_VIDEO) < 0)
{
fprintf(stderr, "Unable to initialize Video and Audio: %s\n", SDL_GetError());
return -1;
}

/*(you can call Video and Audio function here)*/

if(use_joystick = 1)
{
if(SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0)
{
fprintf(stderr, "Unable to initialize Joystick: %s\n", SDL_GetError());
return -1;
}
}

/*(Now Joystick functions are available)*/
return 0;
}

In the example above I also show how to use the SDL_GetError() function. This function works in a similar way the Unix errno system works. When an error occurs SDL_GetError() will get the last error that happened and previous errors are overwritten. SDL_GetError() returns a string describing the error.





Initializing SDL  << Page 2 of 4  >>