Static linking with cmake

Does anyone have any examples of statically linking SDL2 with cmake.

NOTE: Please don’t do this if your project is closed-source. Whenever the version of SDL that you linked breaks due to OS updates, users won’t be able to update it. If you’ve stopped supporting it at that point, then they’re SOL.

If you’re able to do it, there’s pretty robust CMake support through the SDL2-static target. Just add_subdirectory() the base of the library, and add SDL2main and SDL2-static in the target_link_libraries() for your binary. (If you aren’t familiar with how to do that, look up any “linking static libraries” example for cmake.)

The issue comes in with the addons (image, mixer, etc). They don’t have very good (or any) support for static linking, and it’s a maintenance nightmare to fork them just to change the cmake logic (and a big squirrel job to modify them all and get the changes accepted upstream). You also can’t easily do a hacky build from an include() command, because there’s multiple layers of building going on (SDL2-ttf builds freetype with a CMakeLists that tries to find_package(ZLIB), etc). I’ve been working through this on my project, and after a couple days of fiddling with it, I think I’m going to give up and go back to the nightmare of maintaining platform-specific bundles of shared libs to distribute.

Ye I noticed this when I figured it out.
Only managed to statically link sdl2 and sdl2 image gave up on all the libs needed by sdl2 image.

I ended up switching back to shared libs and using a post-build custom command to detect and copy over the relevant ones from the system when I want to package everything. Here’s the script, might be useful to someone

1 Like