问题
I'm following the Lazy Foo tutorial on C++ and SDL2. I'm trying to learn it using regular C and noticed something interesting when following instructions on adding events to detect a close window event.
Here is the code.
#include <stdio.h>
#include <stdbool.h>
#include "SDL2/SDL.h"
bool init();
bool loadMedia();
void close();
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
SDL_Window *gWindow = NULL;
SDL_Surface *gScreenSurface = NULL;
SDL_Surface *gHelloWorld = NULL;
int main(int argc, char *argv[])
{
if(!init()) {
printf("Failed to initialize!\n");
}
else {
if(!loadMedia()) {
printf("Failed to load media!\n");
}
else {
bool quit = false;
SDL_Event e;
while(!quit) {
printf("%d", SDL_PollEvent(&e));
while(SDL_PollEvent(&e) != 0) {
if(e.type == SDL_QUIT) {
quit = true;
}
}
SDL_BlitSurface(gHelloWorld, NULL, gScreenSurface, NULL);
SDL_UpdateWindowSurface(gWindow);
}
}
}
close();
return 0;
}
bool init()
{
bool success = true;
if(SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
success = false;
}
else {
gWindow = SDL_CreateWindow("SDL Tutorial 03", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if(gWindow == NULL) {
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
success = false;
}
else {
gScreenSurface = SDL_GetWindowSurface(gWindow);
}
}
return success;
}
bool loadMedia()
{
bool success = true;
gHelloWorld = SDL_LoadBMP("images/hello_world.bmp");
if(gHelloWorld == NULL) {
printf("Unable to load image %s! SDL_Error: %s\n", "images/hello_world.bmp", SDL_GetError());
success = false;
}
return success;
}
void close()
{
SDL_FreeSurface(gHelloWorld);
gHelloWorld = NULL;
SDL_DestroyWindow(gWindow);
gWindow = NULL;
SDL_Quit();
}
If I compile this with a ".c" extension, it compiles without errors, but selecting the "X" on the window title bar does nothing. If I change said extension to ".cpp", the "X" works as intended.
I'm using the following command to compile the code.
gcc main.c -w -lSDL2 -o main
Any ideas why this may work with C++, but not with C?
回答1:
The function SDL_PollEvent will remove the event from the internal event queue if an address of an SDL_event object is passed to it.
The printf call, that also calls the function SDL_PollEvent, before the event loop which will remove the quit event from the queue. This means the event loop won't find this event:
printf("%d", SDL_PollEvent(&e));
while(SDL_PollEvent(&e) != 0) {
if(e.type == SDL_QUIT) {
quit = true;
}
}
If you only want to check if there are events pending in the queue, then use the function SDL_PollEvent with a NULL argument:
printf("%d", SDL_PollEvent(NULL));
来源:https://stackoverflow.com/questions/39562704/cant-close-window