I'm planning on writing a small 2D game engine in C++, using SDL2 for rendering. I want to write a wrapper library for SDL2 to make it easier to use for myself. How can I link this library with SDL2 using CMake?
-
I believe its pretty much the same as any library when using CMake. Here is an example: [https://trenki2.github.io/blog/2017/06/02/using-sdl2-with-cmake/](https://trenki2.github.io/blog/2017/06/02/using-sdl2-with-cmake/) – drescherjm Jan 30 '21 at 13:57
-
1Related if not a duplicate: [https://stackoverflow.com/questions/28395833/using-sdl2-with-cmake](https://stackoverflow.com/questions/28395833/using-sdl2-with-cmake) – drescherjm Jan 30 '21 at 13:59
1 Answers
So you want your application to link against the wrapper library like this:
Application --> Wrapper lib --> Actual lib
The steps are:
1. Locate the actual library
Try the simpliest way to find an installed library on your system:
find_package(SDL2 REQUIRED)
That should be enough for newer cmake releases. For older versions - see linked questions about how to locate SDL2 with CMake.
2. Create a pseudo-target for that library
The first step left you with bare cmake variables SDL2_INCLUDE_DIRS
and SDL2_LIBRARIES
. Though it's possible to use them as is, it would be much more convenient to combine them in a single target, and use that target through the rest of your CMakeLists.txt file. Creating an INTERFACE target for an external library is somewhat easier than creating an IMPORTED target, so:
add_library (external.sdl2 INTERFACE)
target_include_directories(external.sdl2 INTERFACE ${SDL2_INCLUDE_DIRS})
target_link_libraries (external.sdl2 INTERFACE ${SDL2_LIBRARIES})
Now, every time you link anything againts the target external.sdl2
, both include directories and the actual library will be pulled in automatically.
3. Define the target for your wrapper library
add_library(my_wrapper STATIC
my_wrapper.cpp
)
target_link_libraries(my_wrapper
external.sdl2
)
Note: you don't need explicit include_directories
any more.
4. Define the target for your main executable
add_executable(my_game
my_game.cpp
)
target_link_libraries(my_game
my_wrapper
)
Likewise, you don't have to mention SDL2 in target libraries, not include directories; they will be added implicitly because my_wrapper
target uses it.
P.S. Since this is a C++ project, why not use SDL2PP, the C++ wrapper on SDL2?

- 1,838
- 6
- 18