SDL (簡單直接媒體層) - 入門
外觀
< SDL (簡單直接媒體層) | 基礎
在本節中,我們將向您展示如何初始化和關閉 SDL 子系統。
#include <stdio.h> /* printf and fprintf */
#ifdef _WIN32
#include <SDL/SDL.h> /* Windows-specific SDL2 library */
#else
#include <SDL2/SDL.h> /* macOS- and GNU/Linux-specific */
#endif
int main (int argc, char **argv)
{
/*
* Initialises the SDL video subsystem (as well as the events subsystem).
* Returns 0 on success or a negative error code on failure using SDL_GetError().
*/
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
fprintf(stderr, "SDL failed to initialise: %s\n", SDL_GetError());
return 1;
}
printf("SDL initialised!");
/* Shuts down all SDL subsystems */
SDL_Quit();
return 0;
}
您可以從這個 GitLab 倉庫 下載本節的原始碼。所有原始碼都儲存在這個 組 中。
SDL2 所需的基本函式位於 <SDL/SDL.h> 庫或 <SDL2/SDL.h> 庫中,具體取決於作業系統,因此上述原始碼使用
#ifdef _WIN32
#include <SDL/SDL.h> /* Windows-specific SDL2 library */
#else
#include <SDL2/SDL.h> /* macOS- and GNU/Linux-specific */
#endif
在為 Windows 機器編寫程式碼時,必須包含
int main (int argc, char **argv)
因為 SDL 會覆蓋 main 宏。根據 SDL 的 FAQWindows
您應該使用main()而不是WinMain(),即使您正在建立一個 Windows 應用程式,因為 SDL 提供了一個WinMain()版本,它在呼叫您的主程式碼之前執行一些 SDL 初始化。如果您出於某種原因需要使用WinMain(),請檢視 SDL 原始碼中的src/main/win32/SDL_main.c,以瞭解您在WinMain()函式中需要執行哪些初始化才能使 SDL 正常工作。
使用 SDL 子系統時,您必須始終先初始化它。在下面的 if 語句中,我們使用標誌 SDL_INIT_VIDEO 初始化 SDL 影片子系統。如果成功,它將返回 0,否則它將返回一個負的錯誤程式碼,並將使用 SDL_GetError 透過 stderr 流列印有關錯誤的資訊。
/*
* Initialises the SDL video subsystem (as well as the events subsystem).
* Returns 0 on success or a negative error code on failure using SDL_GetError().
*/
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
fprintf(stderr, "SDL failed to initialise: %s\n", SDL_GetError());
return 1;
}
您可以使用 | 運算子初始化多個子系統
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0)
{
fprintf(stderr, "SDL failed to initialise: %s\n", SDL_GetError());
return 1;
}
有關 SDL_Init 函式子系統及其標誌的所有資訊,請參閱 SDL Wiki 的 SDL_Init 頁面。
要關閉 SDL 子系統,您必須執行
SDL_Quit();
但是,這隻會關閉主要子系統;關閉 TTF 子系統需要一個不同的函式
TTF_Quit();