I would like to use SDL2, but for some reason the window does not appear.
As far as the log shows, the program seems to be working.However, the window does not appear.
If you know the solution, please take care of it.
#include<iostream>
# include "SDL2/SDL.h"
using namespace std;
int main(intargc, char*argv[])
{
cout<<"Start"<<endl;
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
if(SDL_Init(SDL_INIT_AUDIO)<0){
cout<<"SDL init failed."<endl;
return1;
}
// initialize screen
SDL_Window*window=SDL_CreateWindow("Hello world!", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if(window==NULL){
SDL_Quit();
return2;
}
SDL_Render*render=SDL_CreateRender(window,-1, SDL_Render_PREENTVSYNC);
SDL_Texture*texture=SDL_CreateTexture(render, SDL_PIXELFORMAT_RGBA888,
SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);
if(render==NULL) {
cout<<"Could not create render"<<endl;
SDL_DestroyWindow(window);
SDL_Quit();
return3;
}
if(texture==NULL){
cout<<"Could not create texture"<<endl;
SDL_DestroyRenderer(render);
SDL_DestroyWindow(window);
SDL_Quit();
return4;
}
// prepare memory
Uint32*buffer=new Uint32 [SCREEN_WIDTH*SCREEN_HEIGHT];
memset(buffer,0, SCREEN_WIDTH*SCREEN_HEIGHT*sizeof(Uint32));
// set every 4 bytes as color into memory
for (inti=0;i<SCREEN_WIDTH*SCREEN_HEIGHT;i++) {
buffer[i] = 0x008080FF;
}
// update screen
SDL_UpdateTexture(texture, NULL, buffer, SCREEN_WIDTH*sizeof(Uint32));
SDL_RenderClear(render);
SDL_RenderCopy (render, texture, NULL, NULL);
SDL_RenderPresent(render);
bool quit = false;
SDL_Event;
while(!quit){
while(SDL_PollEvent(&event)){
if(event.type==SDL_QUIT){
quit = true;
};
}
cout<<"Loop"<<endl;
}
// finalize screen
delete [ ] buffer;
SDL_DestroyRenderer(render);
SDL_DestroyTexture(texture);
SDL_DestroyWindow(window);
SDL_Quit();
cout<<"End"<<endl;
return 0;
}
$g++-omain main.cpp`sdl2-config --cflags--libs`-lSDL2
$ ./main
Start
Loop
Loop
Loop
Loop
Loop
// Omitted
Loop
Loop
Loop
Loop^C//ctrl+c
Loop
End
I tried to move it in this environment.The window appears.
If you specify a display as follows, a window may appear.
./main-display: 0.0
If not, the X Server installation and configuration may not work.
© 2025 OneMinuteCode. All rights reserved.