Search code examples
c++cmakesdl-2

Using SDL2 with CMake


I'm trying to use CLion to create a SDL2 project. The problem is that the SDL headers can't be found when using #include's.

My CMakeLists.txt file:

cmake_minimum_required(VERSION 2.8.4)
project(ChickenShooter)

set(SDL2_INCLUDE_DIR C:/SDL/SDL2-2.0.3/include)
set(SDL2_LIBRARY C:/SDL/SDL2-2.0.3/lib/x64)

include_directories(${SDL2_INCLUDE_DIR})
set(SOURCE_FILES main.cpp)

add_executable(ChickenShooter ${SOURCE_FILES})
target_link_libraries(ChickenShooter ${SDL2_LIBRARY})

My test main.cpp:

#include <iostream>
#include "SDL.h" /* This one can't be found */

int main(){
    if (SDL_Init(SDL_INIT_VIDEO) != 0){
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 1;
    }
    SDL_Quit();
    return 0;
}

Thank you for any help you could give me.

Edit: I'm using Windows and CLion is configured to use cygwin64.


Solution

  • Don't set the path to SDL2 by hand. Use the proper find command which uses FindSDL. Should look like:

    find_file(SDL2_INCLUDE_DIR NAME SDL.h HINTS SDL2)
    find_library(SDL2_LIBRARY NAME SDL2)
    add_executable(ChickenShooter main.cpp)
    target_include_directories(ChickenShooter ${SDL2_INCLUDE_DIR})
    target_link_libraries(ChickenShooter ${SDL2_LIBRARY})    
    

    If SDL2 is not found, you have to add the path to SDL2 to CMAKE_PREFIX_PATH, that's the place where CMake looks for installed software.

    If you can use Pkg-config, its use might be easier, see How to use SDL2 and SDL_image with cmake

    If you feel more comfortable to use a FindSDL2.cmake file similar to FindSDL.cmake provided by CMake, see https://brendanwhitfield.wordpress.com/2015/02/26/using-cmake-with-sdl2/