Thursday, August 11, 2016

Compiling SDL Apps on Mac OS X With Just a Makefile

There are wonderful tutorials for the SDL 2D graphics library on Lazyfoo.net that I found. The one thing I would change for the Mac OS instructions is to use a Makefile instead of using the build process in Xcode. I want to use Makefiles because I have more control over the build process and to remove the magical blackbox model of compiling that an integrated IDE imposes. Making a Makefile is not easy because you must link to the SDL libraries and Mac OS X packages libraries into things called frameworks instead of bare headers and static object files like other *nixs do. Mac OS X has special flags for gcc to access frameworks, but once you know the flags using Makefiles is a possibility.

Step 1: Install SDL

As of Mac OS Version 10.11 (El Capitan) Mac OS does not have the SDL library installed by default. SDL can be installed by first downloading a .dmg file on the SDL Downloads Web Page. I use SDL 2.0 for this tutorial.


Step 1.2: after opening the downloaded .dmg file drop the SDL2.framework file into /Library/Frameworks, you'll need to have administrative access to do this and you'll need to use your password to add this file. 

Step 2: Write the 'Hello World' program

Create a new folder to put this simple hello world program into. The program below is a very simple program I called main.cpp.
#include <SDL2/SDL.h>
#include <iostream>
int main( int argc, char* args[] ){
  int rc;
  //Start SDL
  rc = SDL_Init( SDL_INIT_EVERYTHING );
  if(rc){
    std::cout << "Could not init SDL" << std::endl;
    return 1;
  }
  //Quit SDL
  SDL_Quit();
  return 0;
}

All this does is open up a blank SDL instance and immediately exits. Not much of a program, but it does demonstrate that the SDL library has been installed and you can link to it, otherwise your code won't compile or you'll get the "Could not init SDL" message.

Step 3: Write your Makefile

Now you'll need to create your Makefile, again nothing too complex, just called the following file Makefile
CC=g++
EXE=setup
setup: main.cpp
 $(CC) -F/Library/Frameworks -framework SDL2 -o $(EXE) main.cpp
.PHONY: clean
clean:
 rm $(EXE)

Notice the -F and -framework flags. These are the Mac OS X specific gcc compiler flags. -F specifies a path to your frameworks (libaries) and -framwork specifies a specific framework to load. Now you're ready to build your application, go to your terminal in /Applications/Utilities/Terminal and navigate to your hello world folder. Then run make.

You'll notice that a new file setup had been created. If you run this ./setup your terminal will go out of context for a split second and return when the program exits. Congratulations! You can now build SDL applications without the need for Xcode. 

No comments: