c++cmakesdlsdl-2sdl-image

How to use SDL2 and SDL_image with cmake


I'm looking for the simplest way to compile a c++ program using SDL2 and SDL_image with cmake.

Here is my best attempt, after hours of searching:

CMakeLists.txt

project(shooter-cmake2)

cmake_minimum_required(VERSION 2.8)

set(SOURCES
shooter.cpp
classes.cpp
utils.cpp
)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")

add_executable(${PROJECT_NAME} ${SOURCES})

INCLUDE(FindPkgConfig)
PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2_image REQUIRED sdl2_image)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIR})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARY})

I get these errors:

In function `loadTexture(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, SDL_Renderer*)':
undefined reference to `IMG_LoadTexture'
collect2: ld returned 1 exit status

Here is the function call:

#include "SDL.h"
#include "SDL_image.h"

SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){
    SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str());
    texture != nullptr or die("LoadTexture");
    return texture;
}

Solution

  • I think that the following will work, as it finds the libraries on my ubuntu system and the example function you provided can link:

    project(shooter-cmake2)
    
    cmake_minimum_required(VERSION 2.8)
    
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
    
    add_executable(${PROJECT_NAME} src/test.cpp)
    
    INCLUDE(FindPkgConfig)
    
    PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
    PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED SDL2_image>=2.0.0)
    
    INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS})
    TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES})
    

    If cmake is executed with --debug-output it outputs:

    -- Found PkgConfig: /usr/bin/pkg-config (found version "0.26") 
    Called from: [2]    /usr/share/cmake-2.8/Modules/FindPkgConfig.cmake
                [1] $USER/stack-overflow/cmake-sdl2-image/CMakeLists.txt
    -- checking for one of the modules 'sdl2'
    Called from: [1]    $USER/stack-overflow/cmake-sdl2-image/CMakeLists.txt
    -- checking for one of the modules 'SDL2_image>=2.0.0'
    Called from: [1]    $USER/stack-overflow/cmake-sdl2-image/CMakeLists.txt
    

    This made me check the contents of

    /usr/lib/x86_64-linux-gnu/pkgconfig/sdl2.pc
    /usr/lib/x86_64-linux-gnu/pkgconfig/SDL2_image.pc
    

    I noticed that SDL2_image.pc contains Name: SDL2_image which I assumed should match the third parameter to PKG_SEARCH_MODULE for this library.