如何编译用C编写的SDL程序示例?
我正在开始使用SDL和C编程。 我有其他编程语言的经验,但在C中链接/编译库对我来说是新的。 我正在使用Mac 10.8并使用read me( ./configure; make; make install
)中的说明安装了最新的稳定版2.0。 这是我尝试编译的示例代码:
#include #include #include "SDL.h" int main(void) { if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) { fprintf(stderr, "\nUnable to initialize SDL: %s\n", SDL_GetError()); return 1; } atexit(SDL_Quit); return 0; }
当我尝试使用gcc example.c
编译我的脚本时,我收到一个错误:
example.c:3:17: error: SDL.h: No such file or directory example.c: In function 'main': example.c:7: error: 'SDL_INIT_VIDEO' undeclared (first use in this function) example.c:7: error: (Each undeclared identifier is reported only once example.c:7: error: for each function it appears in.) example.c:7: error: 'SDL_INIT_TIMER' undeclared (first use in this function) example.c:8: warning: format '%s' expects type 'char *', but argument 3 has type 'int' example.c:8: warning: format '%s' expects type 'char *', but argument 3 has type 'int' example.c:11: error: 'SDL_Quit' undeclared (first use in this function)
我尝试搜索wiki,教程以及我能找到的任何类型的文档,但是我找不到任何示例如何正确编译使用SDL的C程序的示例。
编译此程序需要做什么?
C初学者的一般提示:自上而下读取错误日志:经常修复第一个错误将解决所有其他错误。 在您的情况下,第一个错误是:
example.c:3:17: error: SDL.h: No such file or directory
正如其他人所说,你需要指示gcc
在哪里找到SDL.h
您可以通过提供-I
选项来完成此操作。
要检查默认情况下安装SDL.h
位置,我会发出
./configure --help
在您构建libsdl
的目录中。 然后查找--prefix
,在Linux下默认前缀通常是/usr/local
。 要编译您的示例,我将发布(在Linux上):
gcc example.c -I/usr/local/include
但是上面的命令编译并链接代码。 编译成功后, gcc
会抛出另一堆错误,其中一个是undefined reference
。
为了防止这种情况,构建示例的完整命令行(至少在Linux上)将是:
gcc example.c -I/usr/local/include -L/usr/local/lib -lSDL
哪里:
-
-I
编译器指向SDL.h
目录, -
-L
使用libSDL.a
(或libSDL.so
)将链接器指向目录, -
-l
指示链接器与库链接,在本例中为libSDL.a
或libSDL.so
。 请注意,缺少lib
前缀和.a
/.so
后缀。
请注意,即使在Linux机器上,我也没有检查此指令(另一方面,我无法访问Mac OS机器)。
还有一件事:默认情况下,带编译和链接示例的二进制文件将被称为a.out
。 要更改它,您可以为gcc
提供-o
选项。
我发现你可以使用一个名为pkg-config
的工具找出特定库所需的编译器标志。
$ 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)
如果您使用的是Makefile
,则需要在命令前加上shell
:
all: gcc example.c $(shell pkg-config --cflags --libs sdl2)