SDL (Simple DirectMedia Layer) 是廣受歡迎的跨平台多媒體庫。本文記錄在 Windows XP SP3 上,使用 Visual C++ 6.0 建置 SDL 1.2.14 開發環境的完整步驟,並附上可直接編譯執行的測試程式碼。
SDL-devel-1.2.14-VC6.zip(官網下載)lib 資料夾下的 SDL.lib、SDLmain.lib 複製到 VC6 安裝目錄的 lib 資料夾。SDL.dll 複製到 C:\WINDOWS\SYSTEM32。若需將程式移植到未安裝 SDL 的電腦,請將 SDL.dll 隨程式一併發布。include 目錄下建立 SDL 子目錄,將開發包 include 內所有檔案複製進去。Project → Settings → C/C++ → Code Generation,將 Use run-time library 設為 Multithread DLL。Link → Input → Object/library modules 填入 SDL.lib SDLmain.lib。.cpp 檔,即可編譯執行。#include <stdlib.h>
#include "SDL/SDL.h"
SDL_Surface *screen;
void render()
{
if (SDL_MUSTLOCK(screen)) {
if (SDL_LockSurface(screen) < 0) return;
}
int tick = SDL_GetTicks();
int i, j, yofs, ofs;
yofs = 0;
for (i = 0; i < 480; ++i) {
for (j = 0, ofs = yofs; j < 640; ++j, ++ofs) {
((unsigned int*)screen->pixels)[ofs] = i * i + j * j + tick;
}
yofs += screen->pitch / 4;
}
if (SDL_MUSTLOCK(screen))
SDL_UnlockSurface(screen);
SDL_UpdateRect(screen, 0, 0, 640, 480);
}
int main(int argc, char *argv[])
{
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
exit(1);
}
atexit(SDL_Quit);
screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
if (!screen) {
fprintf(stderr, "Unable to set 640x480 video: %s\n", SDL_GetError());
exit(1);
}
while (1) {
render();
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN: break;
case SDL_KEYUP:
if (event.key.keysym.sym == SDLK_ESCAPE)
return 0;
break;
case SDL_QUIT:
return 0;
}
}
}
return 0;
}
SDL.h,請確認步驟 3 標頭檔路徑是否正確。unresolved external symbol _SDL_main 通常是專案類型未選 Win32 Application 或未連結 SDLmain.lib。