【发布时间】:2015-01-11 06:46:50
【问题描述】:
我想将 SDL 与 C 而不是 C++ 一起使用,但我无法让事件工作。 如果它是一个 .c 或 cpp 文件并使用 g++ 编译,则此代码可以完美运行,如果它是一个 .cpp 文件并使用 gcc 编译,它也可以完美运行。但是,如果它是一个 .c 文件并使用 gcc 编译,它编译得很好,但 SDL_QUIT 事件实际上并没有做任何事情,窗口就会永远挂起。
#include<SDL2/SDL.h>
#include <stdio.h>
//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 400;
int init();
int loadMedia();
void mainLoop();
void close();
SDL_Window* window = NULL;
SDL_Surface* screenSurface = NULL;
SDL_Surface* helloWorld = NULL;
int main( int argc, char* args[] ){
if( !init() ){
printf("Failed to initialize!\n");
}
else{
if( !loadMedia() ){
printf("Failed to load media!\n");
}
else{
mainLoop();
}
}
close();
return 0;
}
void mainLoop(){
int quit = 0;
SDL_Event e;
while( !quit ){
while( SDL_PollEvent( &e ) != 0 ){
if(e.type == SDL_QUIT){
quit = 1;
}
}
SDL_BlitSurface( helloWorld, NULL, screenSurface, NULL);
SDL_UpdateWindowSurface( window );
}
}
int init(){
int success = 1;
//initialize sdl
if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0){
printf("SDL could not initialize! SDL_Error: %s\n" , SDL_GetError() );
success = 0;
}
else {
//create 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() );
success = 0;
}
else {
screenSurface = SDL_GetWindowSurface( window );
}
}
return success;
}
int loadMedia(){
int success = 1;
helloWorld = SDL_LoadBMP("images/helloWorld.bmp");
if( helloWorld == NULL ){
printf(" Unable to load image %s! SDL_Error: %s\n", "images/helloWorld.bmp", SDL_GetError() );
success = 0;
}
return success;
}
void close(){
//deallocate surface
SDL_FreeSurface( helloWorld);
helloWorld = NULL;
//Destroy window
SDL_DestroyWindow( window );
window = NULL;
//Quit SDL subsystems
SDL_Quit();
}
【问题讨论】:
-
有问题的代码没有错。您正在执行哪些操作来产生 QUIT 事件?请为您的问题制作完整的可编译最小示例并将其包含在问题中。
-
单击窗口上的 X 按钮,什么也不做。此外,如果我添加其他键或鼠标事件,它们在纯 C 中不起作用,但切换到 C++ 编译器或源代码会导致所有 sdl 事件正常工作
-
如果你坚持不发布完整的例子,那么这个问题是无法回答的。
-
对不起,我误读了您的问题。用完整的示例代码更新了我的第一篇文章。我也在运行 Ubuntu 14.04