目次

HelloSDL-window

作成日: 2023-07-21 (金)

初心者によるC++入門 #31 SDLのウィンドウを表示する

main.cpp

#include <SDL2/SDL.h>
#include <iostream>

int main(int argc, char **argv) {
    int const ScreenWidth = 400;
    int const ScreenHeight = 400;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        std::cerr << "Error: init SDL\n";
        std::exit(1);
    }
    
    SDL_Window *window = SDL_CreateWindow(
            "HelloSDL window",
            SDL_WINDOWPOS_CENTERED,
            SDL_WINDOWPOS_CENTERED,
            ScreenWidth,
            ScreenHeight,
            0);
    if (window == nullptr) {
        std::cerr << "Error: create window\n";
        std::exit(1);
    }
    
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if (renderer == nullptr) {
        std::cerr << "Error: create renderer\n";
        std::exit(1);
    }
    
    bool running = true;
    while (running) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                running = false;
            }
        }
        
        SDL_SetRenderDrawColor(renderer, 100, 100, 255, 255);
        SDL_RenderClear(renderer);
        
        SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
        SDL_Rect rect{100, 150, 150, 100};
        SDL_RenderFillRect(renderer, &rect);
        
        SDL_RenderPresent(renderer);
        
        SDL_Delay(1);
    }
    
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    return 0;
}

Makefile

SRCS = \
	main.cpp
OBJS = ${SRCS:%.cpp=%.o}
DEPS = ${SRCS:%.cpp=%.d}
EXECUTABLE = HelloSDL-window.exe
CXXFLAGS = -IC:\SDL2\include
LDFLAGS = -LC:\SDL2\lib
LDLIBS = -lmingw32 -lSDL2main -lSDL2

.PHONY: all
all: ${EXECUTABLE}

${EXECUTABLE}: ${OBJS}
	${CXX} -o $@ $^ ${LDFLAGS} ${LDLIBS}

%.o: %.cpp
	${CXX} -c -o $@ $< -MMD -MP ${CXXFLAGS}

.PHONY: clean
clean:
	${RM} ${EXECUTABLE} ${OBJS} ${DEPS}

-include ${DEPS}

C:\SDL2の部分は、SDLをインストールした場所を指定します。