Search code examples
clinuxgccsdl

gcc won't compile SDL C Program (undefined reference to SDL functions)


I recently moved to linux and i'm having an issue with compiling SDL C programs using gcc.

The command i'm using:

gcc `sdl-config --cflags --libs` -o main main.c

Even by seperating sdl-config flags:

gcc `sdl-config --cflags` -c main.c
gcc `sdl-config --libs` -o main main.o

I'm getting the same error:

/tmp/ccHYyjKd.o: In function `main':
main.c:(.text+0xe): undefined reference to `SDL_SetMainReady'
main.c:(.text+0x18): undefined reference to `SDL_Init'
main.c:(.text+0x31): undefined reference to `SDL_SetVideoMode'
main.c:(.text+0x54): undefined reference to `SDL_MapRGB'
main.c:(.text+0x6b): undefined reference to `SDL_FillRect'
main.c:(.text+0x77): undefined reference to `SDL_Flip'
main.c:(.text+0x83): undefined reference to `SDL_WaitEvent'
main.c:(.text+0x90): undefined reference to `SDL_Quit'
collect2: error: ld returned 1 exit status

My very simple program:

#include <stdio.h>
#include <stdlib.h>
#define SDL_MAIN_HANDLED
#include <SDL/SDL.h>

int main()
{   
    // SDL Initialize
    SDL_SetMainReady();
    SDL_Init(SDL_INIT_VIDEO);

    // Screen Initialize
    SDL_Surface *screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
    Uint32 screenColor = SDL_MapRGB(screen->format, 255, 255, 255);
    SDL_FillRect(screen, NULL, screenColor);
    SDL_Flip(screen);

    // Main Program Loop
    SDL_Event event;
    do
    {
        SDL_WaitEvent(&event);
    } while (event.type != SDL_QUIT);

    // SDL Quit
    SDL_Quit();

    return 0;
}

Solution

  • Order of arguments to gcc matters a lot.

    Read about Invoking GCC (and documentation of binutils, which gcc uses). Then replace

     gcc `sdl-config --libs` -o main main.o
    

    with

     gcc main.o  `sdl-config --libs` -o main
    

    Better yet, learn how to use GNU make (it is often using GNU bash) and use a Makefile inspired by this answer...

    Also, always pass -Wall -g to gcc until your program is bug-free (then use -Wall -O2)

    Take inspiration from open source programs on github or gitlab using SDL. Consider also using other open source libraries and frameworks, such as Qt, SFML, GTKmm, etc... And study their example code.