Cmake, downloading and building SDL2

1
2
3
int main() {
   puts("One is not impressed\n");
}

I am not really a fan of cmake or really any build tools if I am honest. All things being equal I would probably use Meson but not everything is equal. For now cmake seems to have won. By won I mean has the best support in IDEs and number of users. I no longer want to fight the tide on this.

I like to use the most recent version of SDL2 but linking to the system installed library (on Linux) is not exactly the best strategy. On window it is a pain to install and set up correctly.

That is until I discovered Cmake can do most of the work for you.

# cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -GNinja ..

cmake_minimum_required(VERSION 3.13 FATAL_ERROR)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)


# Pulling down SDL2
include(FetchContent)

FetchContent_Declare(
        SDL2
        GIT_REPOSITORY "https://github.com/SDL-mirror/SDL.git"
        GIT_TAG release-2.0.10
)

FetchContent_GetProperties(SDL2)
if (NOT sdl2_POPULATED)
    FetchContent_Populate(SDL2)
    add_subdirectory(${sdl2_SOURCE_DIR} ${sdl2_BINARY_DIR})
endif ()

project(game1)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

#
#  Pong
#
add_executable(pong
        src/main.c
        src/input.c
        src/rand.c
        src/gfx.c
        src/text.c
        src/texture.c
        src/time.c
        src/base/arena.c
        src/base/hash_table.c
        src/base/implementations.c
        )

target_link_libraries(pong SDL2main SDL2-static m)
target_compile_options(pong PRIVATE -Wall -Wextra)
# TODO eventually remove this
target_include_directories(pong PRIVATE ${sdl2_SOURCE_DIRS}/include external/glad/include)

This is my full cmake file for a small game I was working on. Really I was after developing a simple collections of tools so I could develop a slightly more complicated game afterwards.

For now though focus on the Fetch content stuff at the top. I am not going to go into details but this will pull down version 2.10 of SDL 2. Build it and make the include/libraries available to you.

You can see near the end of the script I link in SDLmain and SDL-static. I like it and it made me miss the Cargo tool from Rust a whole lot less. Want to upgrade to 2.11 just change the tag number.

In the past I did get it working on windows I think I had to play with setting a define to get it to work.

My library requirement are pretty small when it comes to development so this approach work really well.


339 Words

2019-09-11 23:00 +0000