📅  最后修改于: 2023-12-03 15:13:47.912000             🧑  作者: Mango
SDL(Simple DirectMedia Layer)是一款用于游戏和媒体应用程序开发的跨平台多媒体库,支持音频、图像、鼠标、键盘、操纵杆、高级 2D 图形等功能。本文将介绍如何在 Windows 环境下使用 mingw 编译 SDL 程序。
下载 mingw-w64 安装包并安装:http://mingw-w64.org/doku.php/download
可选安装 MSYS2:https://www.msys2.org/
下载 SDL2 开发库:https://www.libsdl.org/download-2.0.php
解压至某一目录,并将解压目录下的 include
和 lib
目录添加到项目中。
#include <SDL2/SDL.h>
int main(int argc, char* argv[])
{
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_Texture* texture = NULL;
SDL_Event event;
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init failed: %s", SDL_GetError());
return -1;
}
window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
if (window == NULL)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateWindow failed: %s", SDL_GetError());
SDL_Quit();
return -1;
}
renderer = SDL_CreateRenderer(window, -1, 0);
if (renderer == NULL)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateRenderer failed: %s", SDL_GetError());
SDL_DestroyWindow(window);
SDL_Quit();
return -1;
}
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, 640, 480);
if (texture == NULL)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateTexture failed: %s", SDL_GetError());
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return -1;
}
while (1)
{
if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
{
break;
}
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
gcc -o main.exe main.c -lmingw32 -lSDL2main -lSDL2
参数说明:
-lmingw32
:mingw 运行库-lSDL2main
:SDL2 的主函数入口库-lSDL2
:SDL2 库在命令行中输入 main.exe
运行程序,程序窗口应该成功打开。
本文介绍了如何在 Windows 环境下使用 mingw 编译 SDL 程序,希望对有需要的程序员有所帮助。