Skip to content

SDL main docs don't explain how to best manage the main function from non-C languages #14513

@castholm

Description

@castholm

Extracted from #12676, #14502 (comment)

It's not currently clear how users who can't use SDL_main.h (e.g. because they are using a language other than C/C++), and instead need to provide their own entry points, are supposed to handle the main function. They might want SDL to initialize platform-specifics, or hook into SDL's main callback system. The docs only mention SDL_SetMainReady() and SDL_RunApp() in passing, but it's not clear which one is best.

From my own experience using SDL outside of C, I believe the best and most portable practice is to call SDL_RunApp() from your native main function with a callback function that in turn calls SDL_EnterAppMainCallbacks().

// native main function
int main(int argc, char *argv[]) {
    return SDL_RunApp(argc, argv, myMain);
}

// SDL_RunApp callback (declared with a C calling convention)
int SDLCALL myMain(int argc, char *argv[])
{
    return SDL_EnterAppMainCallbacks(argc, argv, myAppInit, myAppIterate, myAppEvent, myAppQuit);
}

// ... declare SDL_AppInit/Iterate/Event/Quit callbacks ...

Using main callbacks is optional, but recommended to avoid needing to write platform-specific code for e.g. Emscripten.

This should work for most platforms. However, on Android you would need to export a function equivalent to myMain above with the symbol name SDL_main, which should be mentioned as a special case.

SDL_SetMainReady() should only be used as a last resort, if the user really can't/doesn't want to use SDL_RunApp(). By not using SDL_RunApp(), you are left entirely to your own devices and need to initialize platform specific details yourself.

Not letting SDL_main.h redefine the main function is an advanced use case, so I don't think this needs to be mentioned upfront in e.g. tutorials or examples. But having this kind of information somewhere in https://wiki.libsdl.org/SDL3/CategoryMain and/or https://wiki.libsdl.org/SDL3/README-main-functions would be great, especially for library authors developing SDL bindings for different languages.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions