How to install/compile SDL2 C code on Linux/Ubuntu

人走茶凉 提交于 2019-12-04 17:41:54

I'll go ahead and clean up that Makefile for you.

CFLAGS = -O3
LDFLAGS =
appname = test

all: $(appname)
clean:
    rm -f $(appname) *.o
.PHONY: all clean

sdl_cflags := $(shell pkg-config --cflags sdl2 SDL2_mixer)
sdl_libs := $(shell pkg-config --libs sdl2 SDL2_mixer)
override CFLAGS += $(sdl_cflags)
override LIBS += $(sdl_libs)

$(appname): test.o
    $(CC) $(LDFLAGS) -o $@ $^ $(LIBS)

Explanation

  • Variables in a makefile should be used with $(...), not ${...}.

  • pkg-config has an entry for SDL_Mixer, sdl-config does not. pkg-config is much more general.

  • using override with the SDL flags allows you to run something like make CFLAGS="-O0 -g" without breaking SDL support.

  • This is actually important: the SDL library flags have to be at the end of the command line, in LIBS, due to the fact that the GNU linker is sensitive to the order in which libraries are specified.

  • You don't need explicit rules for .c files, because GNU Make has implicit rules which are just fine.

Note that there are some very important features missing from this makefile. For example, it won't automatically recompile things when you change your header files. I would recommend that you use another build system, such as CMake or SCons, which handles this automatically. You can also do it with Make, but you'd have to paste several arcane lines of code into your makefile.

You can use sdl2-config as suggested by the SDL Linux FAQ to get the required compiler and linker flags:

SDL_CFLAGS := $(shell sdl2-config --cflags)
SDL_LDFLAGS := $(shell sdl2-config --libs)

CFLAGS := $(SDL_CFLAGS) -O3
LDFLAGS := $(SDL_LDFLAGS) -lSDL_mixer

It will find the location of your SDL.h and return the corresponding flag (e.g. -I/usr/include/SDL2 in your case) among other flags it deems necessary (e.g. for me it gives -D_THREAD_SAFE). And then you can simply #include <SDL.h>, which is the standard way to include SDL.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!