How to compile an example SDL program written in C?

I found out you can use a tool called pkg-config to find out the compiler flags expected for a specific library.

$ pkg-config --cflags --libs sdl2
-D_THREAD_SAFE -I/usr/local/include/SDL2 -I/usr/X11R6/include -L/usr/local/lib -lSDL2

$ gcc example.c $(pkg-config --cflags --libs sdl2)

If you are using a Makefile, you need to prefix the command with shell:

all:
    gcc example.c $(shell pkg-config --cflags --libs sdl2)

A general hint for C beginners: read error logs top-down: often fixing first error will resolve all other. In your case first error is:

example.c:3:17: error: SDL.h: No such file or directory

As others have said, you need to instruct gcc where to find SDL.h. You can do this by providing -I option.

To check where SDL.h is installed by default I would issue

./configure --help

in the directory where you did build libsdl. Then look for --prefix, under Linux default prefix is often /usr/local. To compile your example I would issue (on Linux):

gcc example.c -I/usr/local/include

But the above command compiles and links the code. After successful compilation, gcc would throw another bunch of errors, one of them being undefined reference.

To prevent that, full command line to build your example (on Linux at least) would be:

gcc example.c -I/usr/local/include -L/usr/local/lib -lSDL

Where:

  • -I points compiler to directory with SDL.h,
  • -L points linker to directory with libSDL.a (or libSDL.so),
  • -l instructs linker to link with library, in our case libSDL.a or libSDL.so. Note that the lib prefix and .a/.so suffix is missing.

Please note that I didn't check this instruction, even on Linux machine (on the other hand I have no access to Mac OS machine).

One more thing: by default binary with the compiled and linked example will be called a.out. To change that you can provide -o option to gcc.

Tags:

C

Sdl