2 Initializing SDL



Table of Contents

  1. Introduction
  2. Initializing SDL
  3. Keyboard Input
  4. Drawing Graphics
  5. Playing Sound
  6. Drawing Text
  7. Regulating FPS
  8. Enumerations and Random Numbers
  9. Bounding Box Collision Detection
  10. Planning the Game
  11. Super Basic Game Structure
  12. Wrapping up


Download entire guide as ODT


Part 2 – Initializing SDL


Before you can have fancy graphics and a sweet game, you first need to display a window on the screen!

SDL initialization:

When you create a new project, make a blank console application. You can get to the linker by Project > Compiler options in Code::Blocks or Project > Project Options in DevC++.

In the linker, you’ll write

-lmingw32 -lSDLmain -lSDL -lSDL_mixer
#include "SDL/SDL.h"

int main( int argc, char *args[] )
    /* Initialization */
    SDL_Surface *buffer;

    bool fullscreen = false;

    if ( fullscreen == true )   // For fullscreen
        buffer = SDL_SetVideoMode( 640, 480, 32, SDL_SWSURFACE | 		SDL_FULLSCREEN );
    else                        // For windowed
        buffer = SDL_SetVideoMode( 640, 480, 32, SDL_SWSURFACE );

        Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ); // init sound

    // Set window caption
    SDL_WM_SetCaption( "Yay!", NULL );
    /* End Initialization */

    /* Game loop and such would go here */

    /* Close SDL.  Normally, you'd free surfaces, but since 
	SDL_SetVideoMode was used on buffer, SDL_Quit knows to
	automatically free that for us. */

    return 0;

This will create a window but then immediately close it, as we do not have a game loop yet. For SDL, you need to have int argc, char *args[] in your main parameter list.

Also, before you can use Mix_OpenAudio to initialize sound, you have to set up an additional library in SDL.

Check out LazyFoo’s Setting up SDL Extension Libraries tutorial
and get SDL_mixer files from The SDL page.

Double Buffering

Normally with a game, you will use double buffering. This will keep the screen from flickering. Basically, it will draw everything to a surface (surface for SDL, bitmap for allegro), and once everything’s all drawn to this surface, it is drawn to the screen all at once.

Cleaner Code

The initialization functions should not be put in main. Normally, I would create a “Game” or “System” class, and put these into the constructor or a Setup function. That way, you will just have something like this:

int main()
	System myGame;

	return 0;

One of your goals in writing games is to keep main as small as possible, and try to find a balance between Object Oriented code and using more C-style techniques where appropriate. While our computers don’t really need optimized code, you can go overboard with OO techniques.

Make sure your exe works right!

Make sure you keep SDL.dll in your game’s folder (same directory as the .exe)!


This tutorial © Rachel J. Morris, 2009

Print Friendly