Dugan Chen's Homepage

Various Things

Building SDL2 programs with CMake and PkgConfig

Here’s what I feel is currently the easiest and safest way to build SDL2 programs.

First, you should never be writing Makefiles by hand. You should be generating them. And for generating Makefiles, CMake is more or less the current standard.

How does CMake detect where a library and its header files are installed? Well, you can read about it in CMake: How To Find Libraries. The standard way is that either CMake or the library provides a module for detecting the library’s installation paths. Well, neither CMake nor SDL2 include an SDL2 CMake module. You could just find one online and use it (google for “FindSDL2.cmake”). But I think there’s a better way.

What SDL2 does include is integration into PkgConfig. You can have CMake query PkgConfig for SDL2’s library and header directories.

Here’s a sample SDL2 program.

#include "SDL.h"
int main()
    return 0;

There are several reasons this is a good test program. First, the header inclusion follows the current standard, which is “SDL.h”, not <SDL2/SDL.h>. Second, it includes an identifier that was added in SDL2, so that if the SDL1 headers are included by mistake, you’d know. It also actually makes SDL calls, so that you’d know if the SDL2 libraries aren’t being linked correctly.

Well, let’s call that file sdl2test.c.

And here’s the CMakeLists.txt file to build it:



ADD_EXECUTABLE(sdl2test sdl2test.c)


The rest is obvious if you’ve ever used CMake. First, you begin in a directory containing these two files:

$ cd sdltest
$ ls

Just let CMake generate the Makefile, then make the project and run it.

mkdir build
cd build
cmake ..