SDL:Tutorials:Setup

From GPWiki
Jump to: navigation, search

Setting up your SDL build environment can be a little tricky on some platforms, but the instructions below should help you on your way to SDL mastery.

The current version of SDL can be found at the SDL download page.

Windows: MinGW

MinGW and SDL: Windows Development

SDL (Simple DirectMedia Layer) is a very powerful, low-level, cross-platform, high-performance multimedia library. If you are unfamiliar with this library I recommend going to the SDL website and having a look around for an hour or nine. Browse the documentation and the header files, and be sure to read the license so you know what you have the rights to use and how you may use it.

Now, assuming you intend to compile SDL apps using the free MinGW compiler (MinGW?), get the latest version of the SDL from the download section on the SDL website. Get the Development Runtime for Win32, the MinGW version. SDL users tend to favour MSVC when on Windows, so some of the MinGW-specific information is a bit sparse. As-is, the development runtime package needs to be configured and installed before you can compile with it. This requires the help of a more unix-like command line shell, either Cygwin (configured to use MinGW) or MSYS from mingw.org (as described in the first section).

Instead of doing this, which will install the libraries and headers into your MinGW system, I prefer to keep SDL separate so I can easily switch between versions of SDL and MinGW just by re-naming the folder.

Furthermore, on Windows, you will most likely ship your app with the SDL DLLs, as opposed to compiling them statically to your app. In which case, you should take advantage of the MSVC-compiled DLL available from libsdl.org, which will in all likelyhood be better optimized than what MinGW will produce. Dynamically linking also gives the user the opportunity to upgrade the SDL DLLs themselves later if need be (or if they choose to share a single SDL.dll with all their apps by placing it in the Windows System folder). Statically linking will also tie your app to the LGPL which SDL was released under.

So, to create a quick-and-dirty standalone SDL SDK which you can use with MinGW, follow these steps:

Begin by unpacking the SDL development runtime archive to a temporary directory. You need to find the header files, the static-link libraries, and the SDL.dll file. These should be found (assuming the packaging hasn't changed since this writing) within another archive called i386-mingw32msvc.tar.gz that should have been created while extracting the first archive. Extract this into another temporary directory. From that you need the headers (.h) and libs (.a), including the dll. For development purposes, you might put those into a directory structure as follows:

SDL/include/*.h
   /lib/*.a,*.dll

Then put a copy of the SDL.dll into the directory your final executable target will reside so that Windows can do the run-time linking when you start up your app. Or, you can place this dll into your Windows directory if you want share that same dll with multiple SDL apps.


The only trick in getting this to compile now is to add the include path (eg: -I../SDL/include), the linker path (eg: -L../SDL/lib), and then finally adding the libraries themselves in the right order. Use:

-lmingw32 -lSDLmain -lSDL

Also, don't forget to add the -mwindows flag, if your IDE doesn't add it automatically (in addition to whatever other libraries you want to link). If you don't put them in the right order, you'll get a linker error complaining about the missing symbol WinMain@16.


If you're using MinIDE, add "mingw32 SDLmain SDL" to the Target Switches -> Linker dialog box, in the "Libraries" edit field.


What is this libSDLmain.a file? It is built from the source file SDL_main.c, in the sdl/src/main/win32 directory (when on Win32 platform). It contains the bare framework for a Windows app, including the essential WinMain function which is a Windowed application's entry-point. If for whatever reason you are having insurmountable problems linking to libSDLmain.a, or if you have a specific need to alter the 'WinMain' or add other platform-specific calls, you can simply add this source file to your project in its place to resolve the link errors and then modify it to your heart's content. I am not recommending this approach, it is only here for your information and to give some insight into how SDL works on Windows.

MinGW and SDL_image

SDL_image is an invaluable add-on library that allows you to use a wide variety of image formats with SDL, including BMP, JPG, GIF, PNG, TGA, PCX and many more (as opposed to just BMPs with SDL alone).

If you want to get up and running quickly without re-compiling from source, simply grab the runtime development package. This time however, you can use the MSVC package. You can link directly to the SDL_image.lib file as it only requires plain vanilla C linkage (no C++ or other MinGW-specific WinMain). Just extract the archive to a location and remember to set the include and lib paths when you compile.

The documentation site for SDL_image is clear and straightforward. It also has an excellent example source to try which serves as a great little intro to both SDL and SDL_Image at the same time. Assuming your SDL/ and SDL_image/ directories are at the same level, create another folder at that same level, called viewimage. Grab the viewimage.c source from the demos directory, as well as a few image files to test. Put the files you download in the viewimage folder. Then you can use this makefile to build the test app:

make -f viewimage.makefile

MinIDE users will just build an SDL project as usual, but add the SDL_image.lib file to the project by dragging that file's icon into the target window, and adding ../SDL_image/include to the include path.

Finally, copy all the .dll files (zlib.dll, jpeg.dll, libpng1.dll, SDL_image.dll and SDL.dll) to the viewimage directory so the app can find them when you run it. The app is a command-line app, so pull up a command prompt and cd to that directory. Test it by running it with the name of one of the demo images:

Windows: Dev-C++

  1. Download and install DEVCPP4.9.9.2, (note install to recommended directory as some gcc programs don't like spaces in path names)
  2. Download the latest SDL devpak (1.2.12 is latest) http://devpaks.org/details.php?devpak=200. Install by double-clicking on it.

That's all you should need for basic SDL programs on windows9x/Me/2K/XP

  1. If you want to use the SDL_mixer library (for sound and music), download the devpak for it SDL_mixer1.2.6 and install it.

Your build environment is now set up. To create an SDL project, perform the following steps.

  1. Open Dev-C++ and from the File menu, select NewProject.
  2. Click on the Empty Project icon, give your project a name, and click Ok.
  3. Use the file browser to decide where to save your project's DEV file, and click Save.
  4. Under the Project menu, select Project Options.
  5. Click the Parameters tab, and in the Linker textbox enter "-lmingw32 -lSDLmain -lSDL -lSDL_mixer" (without the quotes) then click Ok.
    • NOTE: If you do not want the console window to appear when your program runs, you will need to add -mwindows to the end of your linker string!
  6. You can now use Dev-C++ to add your source code to the project. When you're done, from the Execute menu, select Compile. This will create an executable file in your project's root directory.
  7. Before you can run the executable, you will need to copy SDL.dll and SDL_mixer.dll to your project's root directory, or if you prefer, you can copy the two DLLs to your \windows\system or \windows\system32 folder. Windows must be able to find the DLLs, or you'll get an error when you attempt to run the executable.

If you have any difficulties setting up your Dev-C++ build environment, or if you have trouble getting your code to compile and execute, drop by our community forums and post a question. Someone will help you get things running!

Windows: MSVC++ .NET

  1. On the SDL download page, get the latest version of the Windows-VC development libraries.
  2. If you want to use the SDL_mixer library (for sound and music), download the Windows-VC development libraries for SDL_mixer.
  3. Uncompress the SDL and SDL_mixer libraries to your local drive.
  4. Consolidate the SDL includes and libraries with the SDL_mixer includes and libraries, so that they're all in a single set of \include and \lib folders. It's easier this way!
  5. Launch Visual Studio .NET, but do not open a project or solution.
  6. From the Tools menu, select Options...
  7. In the tree view, click on Projects and then select VC++ Directories.
  8. In the Show directories for box, select Include files.
  9. Click the new-folder icon, and browse to the \include directory where you consolidated your SDL and SDL_mixer header files.
  10. In the Show directories for box, you now need to select Library files.
  11. Click the new-folder icon, and browse to the \lib directory where you consolidated your SDL and SDL_mixer library files.
  12. Click OK.

Your build environment is now set up, and VC++.NET will now know where to find the SDL and SDL_mixer headers and libraries. To create an SDL project, perform the following steps.

  1. Launch Visual Studio .NET and from the File menu, select New and then Project...
  2. In the tree view, expand Visual C++ Projects and select Win32.
  3. If you don't want a console window to appear when your program is executed, select Win32 Project. Otherwise, select Win32 Console Project. Give your project a name and location, then click OK.
  4. From the Project menu, select Properties... at the bottom of the menu.
  5. In the tree view, expand C/C++ and select Code Generation.
    • NOTE: For some users, the C/C++ item in the tree will only appear if you have a .cpp file in your project, so if you're having trouble here, add a blank .cpp to your project.
  6. Set the Runtime Library value to Multi-threaded DLL or Multi-threaded Debug DLL.
    • NOTE: The SDL Windows FAQ states that this step is necessary because, "SDL is dynamically linked with the multi-threaded version of the Microsoft Visual C runtime."
    • ALSO NOTE: If you plan on running the VC++ debugger with SDL you will have to pass the value SDL_INIT_NOPARACHUTE to SDL_Init in order for debugging to succeed!
  7. We're still in the Properties dialog. In the tree view, now expand Linker and select Command Line.
  8. In the Additional Options field, enter SDL.lib SDLmain.lib and if you are using SDL_mixer, also add SDL_mixer.lib.
  9. VC++ is now set up. You may add your SDL source code to the project, and proceed as normal.
    • NOTE: When you compile your executable, you will need to copy the SDL.dll and SDL_mixer.dll files into the same folder as the EXE. If these DLLs are missing, when the program is executed you will be given an error message regarding the needed DLLs.

If you have any difficulties setting up your MSVC++ .NET build environment, or if you have trouble getting your code to compile and execute, drop by our community forums and post a question. Someone will help you get things running!

MacOS X: Xcode

  1. If Xcode isn't already installed on your MacOS X machine, you should be able to find it on your OSX installation CD-ROMs, or else you can download it from Apple directly.
  2. On the SDL download page, get and install the latest version of the developer framework for MacOS X.
  3. If you want to use the SDL_mixer library (for sound and music), get and install the latest version of the SDL_mixer developer framework for MacOS X.

Your build environment is now set up. To create an SDL project, perform the following steps.

  1. Open Xcode, and from the File menu, select New Project...
  2. From the project list, select SDL Application and click Next.
  3. Give the project a name, and click Finish.
  4. Xcode will create some sample code for you. You can keep this code, or replace it with your own SDL source code.
  5. If you want to use SDL_mixer in the project:
    1. From the Project menu, select Edit Active Target.
    2. From the left-hand tree, select Linker Settings.
    3. In the Linker Flags field, add -framework SDL_mixer
    4. Also, when attempting a build, if you encounter errors involving the SDL_mixer.h header file, you may need to add the SDL include directory (or another directory containing the SDL_mixer.h header file) to your include path.
  6. From the Build menu, select Build and Run.

If you have any difficulties setting up your Xcode build environment, or if you have trouble getting your code to compile and execute, drop by our community forums and post a question. Someone will help you get things running!

Linux: KDevelop

  1. If KDevelop didn't come with your distribution, you'll need to download and install the latest version.
  2. On the SDL download page, get and install the latest version of the development libraries for your hardware platform, or else download the SDL source and compile it yourself.
  3. If you want to use the SDL_mixer library (for sound and music), get and install the latest version of the development libraries for your hardware platform, or else download the SDL_mixer source and compile it yourself.

Your build environment is now set up. To create an SDL project, perform the following steps.

  1. Open KDevelop, and from the Project menu, select New Project...
  2. Expand the C++ tree node, and select Simple SDL Program.
  3. Give your application a name, and click Next four times.
  4. KDevelop will create some sample code for you. If you wish to keep this code, you may have to add the SDL include directory (/usr/include/SDL on most systems) to your include path.
  5. If you're making a project with need for SDL_mixer, you'll have to:
    • Add the line #include "SDL_mixer.h" underneath #include "SDL.h"
    • From the Project menu, select Project Options... and click on Configure Options in the left-hand tree.
    • In the Linker flags field, enter -lSDL_mixer and click OK.
  6. From the Build menu, select Build Active Target and answer Yes to any windows that may pop up.
  7. If the build succeeds, your binary will appear in the /debug/src subdirectory of your project's root.
  8. If you need any library of SDL_image, SDL_net, SDL_mixer, etc. you must add an macro in configure.in
    • Go to you project directory and locate the configure.in file
    • Open it with your favorite editor (like kwrite)
    • Add a CHECK_LIB macro as shown below right under the check for the SDL library
    • Run "Build -> Distclean", "Build -> Automake & Autoconf", "Build -> Configure" (names may vary depending on your locale)

Example-macro for SDL_image:

dnl Checks for libraries. 
dnl Replace `main' with a function in -lSDL_image: 
AC_CHECK_LIB(SDL_image, 
       main, 
       LIBS="$LIBS -lSDL_image", 
       AC_MSG_ERROR([*** SDL_image library not found!]) 
)

Another example for SDL_ttf:

dnl Checks for libraries. 
dnl Replace `main' with a function in -lSDL_ttf: 
AC_CHECK_LIB(SDL_ttf, 
       main, 
       LIBS="$LIBS -lSDL_ttf", 
       AC_MSG_ERROR([*** SDL_ttf library not found!]) 
)

If you have any difficulties setting up your KDevelop build environment, or if you have trouble getting your code to compile and execute, drop by our community forums and post a question. Someone will help you get things running!

NOTE: If you are running KDevelop 4 and higher you can add

 target_link_libraries(file_name SDL pthread)

below

  add_executable(file_name main.cpp)

in file CMakeLists.txt.

1. Next you have to go to Run -> Configure Launches. Select your project and press and hold the + button until you see Project Executables drop down menu option.

2. Follow sub-menu of this option until you get your project title. Another option would be to just press the + button and select your project name on Project Target under Executables.

3. After you configure this option and press OK button, you can build and execute the project.

All Platforms: GCC and G++

  1. If your OS is Windows, you'll need to download and install MinGW. If your OS is MacOS X, GCC and G++ should be available on your OSX installation CDs. Most other operating systems will come with GCC and G++ installed by default.
  2. On the SDL download page, get and install the latest version of the development libraries for your OS and hardware platform, or else download the SDL source and compile it yourself.
  3. If you want to use the SDL_mixer library (for sound and music), get and install the latest version of the development libraries for your OS and hardware platform, or else download the SDL_mixer source and compile it yourself.
  4. Make sure that your SDL and SDL_mixer headers and libraries are in your operating system's PATH, so that GCC and G++ will be able to find the files. The GCC and G++ executables will also need to be in the PATH so that they can be executed from within your project directory.

Your build environment is now set up. To create an SDL project, perform the following steps.

  1. Use your favourite text editor to create an SDL source code file, and call it something like sdltest.c (for C) or sdltest.cpp (for C++).
  2. Use GCC to compile C source code like so: gcc sdltest.c -o sdltest -lSDL -lSDL_mixer
    • This tells GCC to compile the source code in sdltest.c into an executable called sdltest and link in the SDL and SDL_mixer libraries.
    • NOTE: If you're using Windows with MinGW, use the following line instead: gcc sdltest.c -o sdltest.exe -lmingw32 -lSDLmain -lSDL -lSDL_mixer
  3. Use G++ to compile C++ source code like so: g++ sdltest.cpp -o sdltest -lSDL -lSDL_mixer
    • This tells G++ to compile the source code in sdltest.cpp into an executable called sdltest and link in the SDL and SDL_mixer libraries.
    • NOTE: If you're using Windows with MinGW, use the following line instead: g++ sdltest.cpp -o sdltest.exe -lmingw32 -lSDLmain -lSDL -lSDL_mixer

Under Linux, one can use sdl-config to determine what compiler and linker flags are required for SDL.

  • sdl-config --cflags will print out the compiler flags
  • sdl-config --libs will print out the linker flags
  • For example, compile and link against the SDL library
    • g++ sdltest.c -o sdltest `sdl-config --cflags --libs`
  • Another example that uses the SDL_mixer library, as well
    • g++ sdltest.c -o sdltest `sdl-config --cflags --libs` -lSDL_mixer


If you have any difficulties setting up your GCC/G++ build environment, or if you have trouble getting your code to compile and execute, drop by our community forums and post a question. Someone will help you get things running!

Mac OS X: GCC & G++

You must also remember to make sure SDL_Init() is called after main() is reached within the program. Not doing so will cause seemingly random error messages to output to a console, if one is opened.

To compile sources in Mac OS X using GCC/G++, you must link BOTH the SDLmain and SDL libraries, as well as setting the "framework" to "Cocoa". Examples:

gcc sdl.c -lSDLmain -lSDL -framework Cocoa

g++ sdl.cpp -lSDLmain -lSDL -framework Cocoa

Detailed information can be found at the LibSDL FAQ Page.

SCons

SCons is a "software construction tool". It is a new alternative to the make tool and Makefiles.

The following is a minimalistic SConstruct file that is read and parsed by SCons to build your game or application. The following example uses SDL, SDL_mixer and SDL_image for libraries, but you can add more in a similar fashion.

import glob

# create build environment
env = Environment()

# determine compiler and linker flags for SDL
env.ParseConfig('sdl-config --cflags')
env.ParseConfig('sdl-config --libs')

# gather a list of source files
SOURCES = glob.glob('*.cpp')

# add additional compiler flags
env.Append(CCFLAGS = ['-g', '-Wall'])
# add additional libraries to link against
env.Append(LIBS = ['SDL_mixer', 'SDL_image'])

# build target
# output executable will be "game"
env.Program(target = 'game', source = SOURCES)

Instead of doing a glob for all .cpp files we could list them by hand if we wanted to:

SOURCES = "column.cpp \
           columns.cpp \
           globals.cpp \
           jewelmap.cpp \
           playfield.cpp \
           setup.cpp \
           timer.cpp"

As you can see, the glob method is much easier, especially as we add more and more source files to our program.

In the last line of the build file "env.Program(target = 'game', source = SOURCES)", the target is the name of the final executable of our program and source is the list of source files we want to build from.

In the example we have a program that uses 3 libraries: SDL, SDL_mixer and SDL_image. You might be wondering why we run sdl-config to add the SDL library, but later add the SDL_mixer and SDL_image libraries to the LIBS variable. The reason is that sdl-config provides all of the compiler and link flags required by SDL, including the linker flag to include SDL as a library, but that's it. SDL_image and SDL_mixer are add-on libraries to SDL, which means they require all the same compiler and link flags as SDL, but you must also explicitly state that you are using these libraries in addition to the main SDL library.

Note: SCons is "just" a utility library for Python, so you can do all the things you can in Python in SCons scripts as well.

CMake

Much like SCons, CMake is a software construction tool, alternative to the old autotools.

Basic CMakeLists.txt file:

Project ( ProjectName )

set (
   SOURCES
   somefile.cpp
   otherfile.cpp
   main.cpp
)

# REQUIRED does not work in CMake <=2.4.6 for SDL
Find_Package ( SDL REQUIRED )
Find_Package ( SDL_image REQUIRED ) # if using SDL_image

# Workaround for the non-working REQUIRED flag
if ( NOT SDL_FOUND )
   message ( FATAL_ERROR "SDL not found!" )
endif ( NOT SDL_FOUND )

link_libraries (
   ${SDL_LIBRARY}
   ${SDLIMAGE_LIBRARY} # if using SDL_image, obviously
   SDLmain # Sadly not included in SDL_LIBRARY variable
)

add_executable (
   ExecutableName
   WIN32 # Only if you don't want the DOS prompt to appear in the background in Windows
   MACOSX_BUNDLE
   ${SOURCES} # We could've listed the source files here directly instead of using a variable to store them
)