cd /

Setting Up SDL2 with CMake


Installing CMake

Most common distributions have cmake available on their package manager repostories:

1 # Debian based
2 sudo apt install cmake
3 
4 # Arch
5 pacman -S cmake

Install SDL2 libraries

I only know about the debian based ones, if you are on another distro you should look them up.

1 sudo apt install libsdl2-dev libsdl2-image-dev libsdl2-mixer-dev libsdl2-net-dev libsdl2-ttf-dev libsdl2-gfx-dev

Directory Structure

Here is a common directory structure when using cmake to find packages:

├── cmake
│   ├── FindSDL2.cmake
│   ├── FindSDL2_mixer.cmake
│   └── FindSDL2_net.cmake
├── CMakeLists.txt
└── src
    └── main.cpp

You can find the cmake files to find SDL2 and it's components here

Or you can use this simple command:

1 cd cmake
2 wget https://raw.githubusercontent.com/aminosbh/sdl2-cmake-modules/master/FindSDL2{,_gfx,_image,_mixer,_net,_ttf}.cmake

Creating the CMakeLists.txt file

 1 cmake_minimum_required(VERSION 3.13)
 2 project(MyProject)
 3 
 4 # Needed so that cmake uses our find modules.
 5 list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
 6 
 7 find_package(SDL2 REQUIRED)
 8 find_package(SDL2_net REQUIRED)
 9 find_package(SDL2_mixer REQUIRED)
10 find_package(SDL2_image REQUIRED)
11 find_package(SDL2_gfx REQUIRED)
12 find_package(SDL2_ttf REQUIRED)
13 
14 
15 set(SOURCE_FILES
16     src/main.cpp
17     )
18 
19 include_directories(src)
20 
21 add_executable(MyProject ${SOURCE_FILES})
22 target_link_libraries(MyProject SDL2::Main SDL2::Net SDL2::Mixer SDL2::Image SDL2::TTF SDL2::GFX)

And thats it! Now you can remove the SDL2 components you don't want to use.

Building

Following the standard cmake procedure:

1 mkdir build
2 cd build
3 cmake ..
4 make -j${nproc}