2013-10-14 76 views
5

我正在開始使用SDL和C編程。我有其他編程語言的經驗,但在C中鏈接/編譯庫對我來說是新的。我使用的是Mac 10.8,並使用讀我的說明(./configure; make; make install)安裝了最新的穩定版2.0。下面是我在試圖編譯示例代碼:如何編譯用C編寫的示例SDL程序?

#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; 
} 

當我嘗試使用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) 

我試圖尋找維基和教程,以及我能找到的任何類型的文檔,但是我無法在任何地方找到任何示例來說明如何正確編譯使用SDL的C程序。

我需要做些什麼來編譯這個程序?

回答

9

對C初學者一般提示:閱讀錯誤日誌自上而下的:經常固定第一個錯誤將解決所有其他。在你的情況第一個錯誤是:

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

正如其他人所說,你需要指示gcc在哪裏可以找到SDL.h。您可以通過提供-I選項來完成此操作。

若要檢查SDL.h默認安裝我會在你沒有建立libsdl目錄發出

./configure --help 

。然後尋找--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 points鏈接到目錄libSDL.a(或libSDL.so),
  • -l指示鏈接器與庫鏈接,在我們的示例中爲libSDL.alibSDL.so。請注意,前綴lib.a/.so缺失。

請注意,即使在Linux機器上,我也沒有檢查該指令(另一方面,我沒有訪問Mac OS機器)。

還有一件事:默認情況下,編譯和鏈接示例的二進制文件將被稱爲a.out。要改變這種情況,您可以提供-o選項至gcc

+0

這真的很有幫助,謝謝! – Andrew

6

我發現你可以使用一個名爲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)