Search code examples
c++cmakesdlsdl-2

How to build SDL_Image from FetchContent?


I'm attempting to build a C++ program with SDL2 and SDL_Image using CMake by fetching them from their respective GitHub repositories; and it works for the most part! When I ran my code with SDL2 everything built fine, and when I added the code for SDL_Image everything compiled without a problem.

However, things break when I try to add SDL_Image. I get:

fatal error C1083: Cannot open include file: 'SDL_Image.h'

I'm confused how it compiles fine and why the same code works fine for main SDL2.

Here's the relevant part of my CMakeLists.txt:

include(FetchContent)
set(FETCHCONTENT_QUIET FALSE)

# sdl2
FetchContent_Declare(
    SDL2
    GIT_REPOSITORY  https://github.com/libsdl-org/SDL
    GIT_TAG         release-2.0.20
    GIT_PROGRESS    TRUE
)

# sdl2_image
FetchContent_Declare(
    SDL2_IMAGE
    GIT_REPOSITORY  https://github.com/libsdl-org/SDL_image
    GIT_TAG         release-2.0.5
    GIT_PROGRESS    TRUE
)

FetchContent_MakeAvailable(SDL2 SDL2_IMAGE)

set(SDL_LIBRARIES ${SDL_LIBRARIES} SDL2main SDL2-static SDL2_image-static)
target_include_directories("${PROJECT_NAME}" PRIVATE include)

target_link_libraries("${PROJECT_NAME}" PRIVATE ${SDL_LIBRARIES})

My build command:

cmake --build ./build --config debug --target ALL_BUILD --parallel

Solution

  • There are two problems with your CMake file:

    GIT_TAG release-2.0.5

    If you look at the SDL_Image repo at that tag, there's no CMakeLists.txt file. That is indeed the most recent tag, though. But fortunately, according to the docs you can use a git SHA for GIT_TAG. With the most recent git SHA at the time of writing, that would look like this:

    GIT_TAG 97405e74e952f51b16c315ed5715b6b9de5a8a50

    The other error is that SDL2_image-static doesn't exist. You need to change that in your set(SDL_LIBRARIES ...) line to just SDL2_image.

    With those two changes, I'm able to #include SDL_Image.h.