How to refer to SDL2 include path with SDL 2.0.8 as cmake IMPORTED TARGET?


#1

I’m using cmake to build a library depending on SDL2. My Linux distribution recently switched to cmake for building SDL2. Thus, the SDL2Config.cmake provided with it only delivers an SDL2 target to link against.

However, my cmake script needs the SDL2 include path as a variable. How do I access it after this change?


#2

So I had finally time to look at this issue again and found the answer:

The SDL2 target that is provided for cmake has per-target properties that can be accessed using get_target_property. One of them is INCLUDE_DIRECTORIES, which turns out to be empty. However, INTERFACE_INCLUDE_DIRECTORIES is not and contains the correct path to the SDL2 headers. So the solution is to do something like

find_package(SDL2 REQUIRED)
get_target_property(SDL2_INCLUDE_DIRS SDL2::SDL2 INTERFACE_INCLUDE_DIRECTORIES)
target_include_directories(mytarget PUBLIC ${SDL2_INCLUDE_DIRS})

#3

Why would you want that variable? You can simply link against the target and all is done:
target_link_libraries(mytarget PUBLIC SDL2::SDL2)

INCLUDE_DIRECTORIES is for building the target (empty in this case as the target is already build)
INTERFACE_INCLUDE_DIRECTORIES is for consumers. It will be added to INCLUDE_DIRECTORIES of every target that is linked against that target.


#4

Linking directly against SDL is undesirable for what I am trying to achieve. But I need to have the header included. I know that this is a slightly strange sounding case. But I found the solution and posted it here for reference and as courtesy to others who might run into a similar problem.