Init, errors & main callbacksSDL 3.2

SDL_AppInit

A function YOU write: SDL calls it once at startup when you use the main callbacks instead of main().

Signature

SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[]);

How it works

SDL3 offers a second way to structure a program. Instead of writing main() with your own while loop, you #define SDL_MAIN_USE_CALLBACKS before #include <SDL3/SDL_main.h> and write four functions: SDL_AppInit (start), SDL_AppEvent (one event), SDL_AppIterate (one frame) and SDL_AppQuit (end). SDL owns the loop.

Why: on the web (Emscripten), iOS and some consoles a program may not block in its own endless loop. With callbacks the same code runs everywhere.

In SDL_AppInit you call SDL_Init and create the window. Store your state in a struct and put its address in *appstate: SDL passes it back to the other three callbacks.

Parameters

appstatevoid **

Where to store a pointer to your app state. SDL passes it to the other callbacks.

argcint

Number of command-line arguments, as in main().

argvchar *

The command-line arguments, as in main().

Return value

SDL_APP_CONTINUE to start running, SDL_APP_FAILURE to quit with an error, SDL_APP_SUCCESS to quit normally.

Example

example.cpp
1#define SDL_MAIN_USE_CALLBACKS
2#include <SDL3/SDL.h>
3#include <SDL3/SDL_main.h>
4
5struct App { SDL_Window* window; SDL_Renderer* renderer; };
6
7SDL_AppResult SDL_AppInit(void** appstate, int argc, char* argv[]) {
8    if (!SDL_Init(SDL_INIT_VIDEO)) return SDL_APP_FAILURE;
9    auto* app = new App{};
10    if (!SDL_CreateWindowAndRenderer("Game", 1280, 720, 0, &app->window, &app->renderer))
11        return SDL_APP_FAILURE;
12    *appstate = app;
13    return SDL_APP_CONTINUE;
14}
Official SDL wiki