How To Properly Include SDL2 Source Code in Project CMake

Viewed 703

I am confused on how to statically include the source code of SDL2. I am trying to do this to make a library I am working on more portable.

Currently, when I try to include my library in another project it says "Cannot open include file: 'SDL2/SDL.h': No such file or directory".

My Filesystem:

include
--Header Files
src
--Source Files
extern
--SDL2
build

Here is an example of the file causing the error:

#include <iostream>
#include <SDL2/SDL.h> //Error

using namespace std;

/* The code */

Here is an example of my main CMakeLists.txt:

cmake_minimum_required(VERSION 3.7)

set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)

project(MyProject VERSION 1.0.0)

set(SDL2_SOURCE_DIR “${CMAKE_SOURCE_DIR}/extern/SDL2”)
add_subdirectory(extern/SDL2)
add_subdirectory(src)

Here is an example of my src CMakeLists.txt:

set(PROJECT_NAME MyProject)

file(GLOB HEADER_FILES "${CMAKE_SOURCE_DIR}/include/*.h")
file(GLOB SOURCES "*.cpp")

add_library(${PROJECT_NAME} ${SOURCES} ${HEADER_FILES})

target_include_directories(${PROJECT_NAME} PUBLIC "${CMAKE_SOURCE_DIR}/include")

target_link_libraries(${PROJECT_NAME} PRIVATE SDL2main SDL2-static)

set_target_properties( ${PROJECT_NAME}
    PROPERTIES
    ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib"
    LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin"
)
1 Answers

add_subdirectory() will process the subdirectory as a cmake porject (process the provided CMakeLists.txt for SDL). If you read that CMakeLists.txt, you'd see that it add the include directories relative to SDL2_SOURCE_DIR, which is empty by default.

What I would try is to set SDL2_SOURCE_DIR to ${CMAKE_CURRENT_SOURCE_DIR}/extern/SDL2 to make the path absolute. Like that SDL include dirs will be valid everywhere in your project.

You can also manually add the correct includes by using the include_directories() directive.

Related