Why SDL defines main macro?

C++SdlMain

C++ Problem Overview


After having some trouble setting up SDL, I found out that SDL defines a macro that replaces main:

#define main SDL_main

// And then
extern C_LINKAGE int SDL_main(int argc, char *argv[]);

This can also create compilation errors, if the main function doesn't have the argc and argv parameters defined.

This macro gives me headaches just when I see it... Why does SDL need to redefine main? After some more searching, I found that some people #undef main, and use it the normal way.

So this is the question: why does SDL need to redefine main, what does it do? Are there any side effects to undefining it?

One thing I noticed is that SDL redirects standard output and error to files (and I don't want this behavior), and this behavior stops if I undefine main.

C++ Solutions


Solution 1 - C++

Per the SDL Windows FAQ:

> You should be using main() instead of WinMain() even though you are creating a Windows application, because SDL provides a version of WinMain() which performs some SDL initialization before calling your main code. > > If for some reason you need to use WinMain(), take a look at the SDL source code in src/main/win32/SDL_main.c to see what kind of initialization you need to do in your WinMain() function so that SDL works properly.

SDL requires initialization, so it injects its own main function that runs its initialization before calling your "main" function, which it renames to SDL_main so that it does not conflict with the actual main function. As noted in the FAQ, your main function must be of the form

int main(int argc, char* argv[])

Solution 2 - C++

While I agree that it's a strange practice, there are situations where this is a reasonable solution, though it largely depends on the platform. Consider that different platforms have different entry points. Windows is typically WinMain, Linux is main, interacting with Android happens in Java, WinRT uses C++/CX extensions, and so on. Program entry point and APIs can be very platform specific and SDL tries to save you the trouble of having to deal with this. If you're only targeting Windows and SDL is only there to save you the trouble of working with WIN32 API, you might not need it. But if you ever go beyond desktop, you'll find it useful in my opinion.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTibiView Question on Stackoverflow
Solution 1 - C++James McNellisView Answer on Stackoverflow
Solution 2 - C++MelView Answer on Stackoverflow