vscode 中 使用 cmake 配置 sdl2 开发环境。
https://www.libsdl.org/release/SDL2-devel-2.0.22-mingw.zip
解压复制 x86_64-w64-mingw32 中 bin 和 include 两个目录到项目中。
导入头文件路径:
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
)
代码如下:
#include "SDL.h"
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
int WinMain(int argc, char *argv[])
{
//将要渲染的窗口
SDL_Window *window = NULL;
//窗口含有的surface
SDL_Surface *screenSurface = NULL;
//初始化SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
}
else
{
//创建 window
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
{
//获取 window surface
screenSurface = SDL_GetWindowSurface(window);
//用白色填充surface
SDL_FillRect(screenSurface, NULL, SDL_MapRGB(screenSurface->format, 0xFF, 0xFF, 0xFF));
//更新surface
SDL_UpdateWindowSurface(window);
//延迟两秒
SDL_Delay(2000);
}
}
//销毁 window
SDL_DestroyWindow(window);
//退出 SDL subsystems
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