Saturday 3 March 2018

SDL2 static linking with CMake

Getting undefined references while linking SDL2 statically? Read on.


The undefined references may look like these:

C:/msys64/mingw64/lib\libSDL2.a(SDL_windowskeyboard.o):(.text+0xf6): undefined reference to `ImmGetIMEFileNameA'
C:/msys64/mingw64/lib\libSDL2.a(SDL_windowskeyboard.o):(.text+0x144): undefined reference to `ImmGetContext'
C:/msys64/mingw64/lib\libSDL2.a(SDL_windowskeyboard.o):(.text+0x167): undefined reference to `ImmReleaseContext'
C:/msys64/mingw64/lib\libSDL2.a(SDL_windowskeyboard.o):(.text+0x1d4): undefined reference to `ImmGetCompositionStringW'
C:/msys64/mingw64/lib\libSDL2.a(SDL_windowskeyboard.o):(.text+0x1ec): undefined reference to `ImmGetCompositionStringW'
...


That's because those functions are from the dependencies of the SDL2 library, which you have neglected to link to. You can solve this by passing the following linker flags:

-lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lversion -luuid

Here's how to pass the flags in CMake.

find_package(SDL2 REQUIRED)

add_executable(main
    main.cpp
    )

target_include_directories(main
    PRIVATE ${SDL2_INCLUDE_DIRS}
    )

target_link_libraries(main
    PRIVATE ${SDL2_LIBRARIES}
    PRIVATE "-lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 \
    -lole32 -loleaut32 -lshell32 -lversion -luuid"
    )


Curious where the flags come from? If you're using MSYS2 and have installed it via pacman -S mingw-w64-x86_64-SDL2, you can check out C:\msys64\mingw64\bin\sdl2-config.

1 comment:

  1. Actually it was "sdl c++ cmake +blog"

    Your page was in the top 10 on Bing!

    ReplyDelete