我开始使用SDL和C编程.我有其他编程语言的经验,但在C中链接/编译库对我来说是新的.我正在使用Mac 10.8并使用read me(./configure; make; make install)中的说明安装了最新的稳定版2.0 .这是我尝试编译的示例代码:
#include <stdlib.h>
#include <stdio.h>
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用编译我的脚本时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)
Run Code Online (Sandbox Code Playgroud)
我尝试搜索wiki,教程以及我能找到的任何类型的文档,但我找不到任何示例如何正确编译使用SDL的C程序的示例.
编译此程序需要做什么?
smb*_*ear 10
C初学者的一般提示:自上而下读取错误日志:经常修复第一个错误将解决所有其他错误.在您的情况下,第一个错误是:
example.c:3:17: error: SDL.h: No such file or directory
Run Code Online (Sandbox Code Playgroud)
正如其他人所说,你需要指明gcc在哪里找到SDL.h.您可以通过提供-I选项来完成此操作.
要检查SDL.h默认情况下安装的位置,我会发出
./configure --help
Run Code Online (Sandbox Code Playgroud)
在您构建的目录中libsdl.然后寻找--prefix,Linux下默认的前缀经常是/usr/local.要编译你的例子,我会发布(在Linux上):
gcc example.c -I/usr/local/include
Run Code Online (Sandbox Code Playgroud)
但是上面的命令编译并链接代码.编译成功后,gcc会抛出另一堆错误,其中一个错误undefined reference.
为了防止这种情况,构建示例的完整命令行(至少在Linux上)将是:
gcc example.c -I/usr/local/include -L/usr/local/lib -lSDL
Run Code Online (Sandbox Code Playgroud)
哪里:
-I将编译器指向目录SDL.h,-L将链接器指向带libSDL.a(或libSDL.so)的目录,-l指示链接器与库链接,在我们的例子中libSDL.a或libSDL.so.请注意,缺少lib前缀和.a/ .so后缀.请注意,即使在Linux机器上,我也没有检查此指令(另一方面,我无法访问Mac OS机器).
还有一件事:默认情况下,将调用编译和链接示例的二进制文件a.out.要更改它,您可以提供-o选项gcc.
我发现你可以使用一个工具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)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Makefile,则需要在命令前添加shell:
all:
gcc example.c $(shell pkg-config --cflags --libs sdl2)
Run Code Online (Sandbox Code Playgroud)