2

I'm not getting MinGW's g++ to successfully compile SDL programs. Here's my sample program:

#include <SDL.h>

int main( int argc, char* args[] )
{  
  SDL_Init( SDL_INIT_VIDEO );
  SDL_Quit();
  return 0;
}

and here's my command and error report:

C:\Users\briggs_w\Desktop\testSDL>g++ test.cc -IC:\MinGW\include\SDL 
-LC:\MinGW\lib -lSDL2 -lSDL2main -lmingw32

C:\MinGW\lib/libmingw32.a(main.o):(.text.startup+0xa0): undefined reference to `WinMain@16'
collect2.exe: error: ld returned 1 exit status

I copied over everything in SDL2's lib\x64 and i686-w64-mingw32\lib folders to the C:\MinGW\lib folder.

What's missing? At the command line, maybe.

I did look over two threads on similar errors:

Undefined reference to WinMain@16 when using SDL -- doing this

undefined reference to WinMain@16 C++, SDL-2 -- no effect

Community
  • 1
  • 1
Topological Sort
  • 2,733
  • 2
  • 27
  • 54

1 Answers1

3

I compiled your code so that compiler and linker flags were provided by sdl2-config (included in an msys2 package):

gcc -O -Wall test.cpp `sdl2-config --cflags --libs`

$ sdl2-config --cflags

-I/mingw64/include/SDL2 -Dmain=SDL_main

$ sdl2-config --libs

-L/mingw64/lib -lmingw32 -lSDL2main -lSDL2 -mwindows

So at least -lmingw32 is in other position in libraries to be linked and also -Dmain=SDL_main was missing. The library SDL2main is a static library, so it needs mingw32 to be prior to it when linking.

From SDL FAQ for windows

You should be using main() instead of WinMain() even though you are creating a Windows application, because SDL provides a version of WinMain() which performs some SDL initialization before calling your main code. If for some reason you need to use WinMain(), take a look at the SDL source code in src/main/win32/SDL_main.c to see what kind of initialization you need to do in your WinMain() function so that SDL works properly.

If there is something like sdl2-config available in case of any library, I would at least check what it outputs.

J.J. Hakala
  • 6,136
  • 6
  • 27
  • 61
  • If that was the case, then there would have been 'undefined reference to SDL_main', but it isn't. – keltar Jul 23 '16 at 06:52
  • @keltar my guess is that `-mwindows` translates `main` to be `WinMain`, and then `WinMain` in SDL2main library is discarded as duplicate and won't be referenced, and thus SDL_main won't be referenced. – J.J. Hakala Jul 23 '16 at 07:06
  • No, libmingw32.a references WinMain, and cannot find one. ld linker is sensitive to libraries order, especially when libraries are static. Your order is correct so it linked; order in question isn't. – keltar Jul 23 '16 at 07:19
  • @keltar yes, I just that checked that myself i.e. that `-lmingw32` and its position was different in the question and what `sdl2-config --libs` gives. I did not notice that difference when writing the answer. – J.J. Hakala Jul 23 '16 at 07:22