前言
vscode 中 使用 cmake 配置 sdl2 开发环境。
1. 下载 SDL
https://www.libsdl.org/release/SDL2-devel-2.0.22-mingw.zip
解压复制 x86_64-w64-mingw32 中 bin 和 include 两个目录到项目中。
2. 配置 cmake
导入头文件路径:
target_include_directories(main
PUBLIC
${CMAKE_CURRENT_LIST_DIR}
${CMAKE_CURRENT_LIST_DIR}/SDL2/include/SDL2
)
导入动态库:
target_link_libraries(main
PUBLIC
${CMAKE_CURRENT_LIST_DIR}/SDL2/bin/SDL2.dll
)
代码如下:
add_executable(main "")
target_sources(main
PRIVATE
${CMAKE_CURRENT_LIST_DIR}/main.c
PUBLIC
${CMAKE_CURRENT_LIST_DIR}/main.h
)
target_include_directories(main
PUBLIC
${CMAKE_CURRENT_LIST_DIR}
${CMAKE_CURRENT_LIST_DIR}/SDL2/include/SDL2
)
target_link_libraries(main
PUBLIC
${CMAKE_CURRENT_LIST_DIR}/SDL2/bin/SDL2.dll
)
3. 实现代码
代码如下:
#include "SDL.h"
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
int WinMain(int argc, char *argv[])
{
SDL_Window *window = NULL;
SDL_Surface *screenSurface = NULL;
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
}
else
{
window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL)
{
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
}
else
{
screenSurface = SDL_GetWindowSurface(window);
SDL_FillRect(screenSurface, NULL, SDL_MapRGB(screenSurface->format, 0xFF, 0xFF, 0xFF));
SDL_UpdateWindowSurface(window);
SDL_Delay(2000);
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
注意此处使用 WinMain 作为入口函数,如果使用 main,则需要添加 #undef main,如下:
#undef main
int main(int argc, char *argv[])
{...}
总结
程序运行时需要动态调用 SDL.dll,需要将 SDL.dll 文件复制到程序所在位置,或者将 SDL.dll 复制到 “C:\Windows\System32” 这个目录下一劳永逸。
如果出现报错 undefined reference to `WinMain’,需要按照 “3. 代码实现” 部分完成入口函数的修改。
交流
项目仓库:https://github.com/dissor/c-libnes/tree/main/examples 微信公众号:物联指北 B站:物联指北 千人企鹅群:658685162
|