Home > Enterprise >  SDL mingw static lib linking errors
SDL mingw static lib linking errors

Time:05-10

I'm trying to compile a simple SDL program using Mingw w64. Here is my code:

test.c

#include "SDL2/SDL.h"
#include <stdio.h>

int main( int argc, char* args[] )
{
  SDL_Window     *window;

  SDL_Init(SDL_INIT_VIDEO);

  window = SDL_CreateWindow("SDL2 Window", 100, 100, 640, 480, 0);

  if(window==NULL)
  {
    printf("Could not create window: %s\n", SDL_GetError());
    return 1;
  }

  SDL_Delay(3000);

  SDL_DestroyWindow(window);

  SDL_Quit();

  return 0;
}

and here is the command I'm using to compile the program:

g   -o text.exe test.c -I./include -L./lib -lmingw32 -lSDL2main -lSDL2

but when I compile the program, I get hundreds of linking errors that look like this:

./lib/libSDL2.a(SDL_wasapi_win32.o): In function `WASAPI_PlatformInit':
/Users/valve/release/SDL/SDL2-2.0.22-source/foo-x64/../src/audio/wasapi/SDL_wasapi_win32.c:255: undefined reference to `__imp_CoCreateInstance'

I downloaded the library from the second link down in the windows development libraries section on the official SDL website, and took the libraries from the following directory:

SDL2-2.0.22\x86_64-w64-mingw32\lib

The contents of ./lib are:

libSDL2main.a
libSDL.a

What is the problem and how can I fix it?

CodePudding user response:

You have two options, depending on your intent:

  • If you want to link SDL2 dynamically (this should be your default course of action), you need to add libSDL2.dll.a to your library directory. Then libSDL2.a will be ignored and can be removed. It should just work, no other changes are needed.

  • If you want to statically link SDL2, you need more linker flags. The exact flags are listed in sdl2.pc in the Libs.private section.

    As of SDL 2.0.22, those are: -Wl,--dynamicbase -Wl,--nxcompat -Wl,--high-entropy-va -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lsetupapi -lversion -luuid.

    Those should be added to the right of -lmingw32 -lSDL2main -lSDL2.

    You also might want to add -static to statically link everything, including the standard library. (What's the point of statically linking SDL2, when your program still needs the DLLs of the standard library to work?) It also makes the linker prefer libSDL2.a to libSDL2.dll.a if both are available, meaning you don't need to worry what's in your library directory.

  • Related