SDL2测试程序无运行无报错,请求排查方向
问题:SDL2初始化测试程序无输出无反应
尝试用SDL2捕获游戏手柄输入,编写了一个简单的测试程序,但运行后无任何反应,既没有错误提示,也没有构建错误。程序运行后无任何输出内容。
测试源码
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> //for sleep #include <stdatomic.h> #include <stdbool.h> #include <stdint.h> #include "SDL.h" int main(int argc, char *argv[]) { /* SDL test */ if(SDL_Init(SDL_INIT_GAMECONTROLLER) < 0) { perror("Failed to initialize SDL2 library\n"); return EXIT_FAILURE; } else printf("SDL2 initialized\n"); printf("Test message"); return EXIT_SUCCESS; }
CMakeLists.txt配置
cmake_minimum_required(VERSION 3.30.1) project(sandbox_project VERSION 1.0 LANGUAGES C) add_executable(sandbox_project WIN32 ${SOURCES}) # define the source files for the project target_sources(sandbox_project PRIVATE src/sandbox_main.c src/ring_buffer/ring_buff.h src/ring_buffer/ring_buff.c ) # add the path of the cmake configuration files list(APPEND CMAKE_PREFIX_PATH "D:/Everyngineering/programming/general_c_cpp/libraries/SDL2-devel-2.30.7-mingw/SDL2-2.30.7/cmake") find_package(SDL2 REQUIRED) # include directories target_include_directories(sandbox_project PRIVATE ${SOURCE_DIR}/src PRIVATE ${SOURCE_DIR}/src/ring_buffer PRIVATE ${SDL2_INCLUDE_DIRS} ) # include libraries target_link_libraries(sandbox_project PRIVATE ${SDL2_LIBRARIES}) # specify C standard set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED True) # specifying the executable output set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin/)
环境说明
- 使用VSCode + CMake构建项目
- 采用预编译的SDL2开发库,未自行编译
- 已将SDL2.dll放置在可执行文件所在目录
- 项目结构:src目录下包含
sandbox_main.c,以及ring_buffer子目录(内含ring_buff.h和ring_buff.c),可执行文件输出到bin目录
解决方向
1. 移除WIN32子系统配置
CMake中add_executable使用了WIN32参数,这会生成窗口程序,默认没有控制台输出,所以printf的内容无法显示。修改为:
add_executable(sandbox_project ${SOURCES})
重新构建后运行,就能看到控制台输出了。
2. 修复SDL错误信息输出方式
perror无法获取SDL的错误信息,SDL有专门的错误获取函数SDL_GetError(),替换错误输出代码:
if(SDL_Init(SDL_INIT_GAMECONTROLLER) < 0) { printf("Failed to initialize SDL2 library: %s\n", SDL_GetError()); return EXIT_FAILURE; }
3. 刷新标准输出缓冲
printf默认是行缓冲,没有换行符的内容不会立即输出。给所有printf添加换行符,或者在return前手动刷新缓冲:
printf("Test message\n"); // 或者在return前添加: fflush(stdout);
4. 验证SDL初始化范围
先尝试用SDL_INIT_EVERYTHING初始化所有SDL子系统,确认SDL本身能否正常初始化,缩小问题范围:
if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
5. 修正CMake变量错误
SOURCE_DIR未定义,应该使用CMake内置的CMAKE_SOURCE_DIR变量,否则可能导致头文件路径错误:
target_include_directories(sandbox_project PRIVATE ${CMAKE_SOURCE_DIR}/src PRIVATE ${CMAKE_SOURCE_DIR}/src/ring_buffer PRIVATE ${SDL2_INCLUDE_DIRS} )
内容的提问来源于stack exchange,提问作者Nightek
相关产品推荐
相关产品推荐

