Search code examples
c++cross-platformsfml

extern int main(int argc, char* argv[]) use?


I've been reading SFML's source code. I found the way it wraps the win32 in a fashion like this:

#ifdef _WIN32 //something like that
#include <windows.h>
extern int main(int argc, char* argv[]);
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT)
{
   return main(__argc, __argv);
}
#endif

so line 4 I see this typical win32 program entry. however what are the extern main and return main(__argc, __argv) doing?

what's __argc with the underscore?

as in my own main function after loading SFML, all I need is to write int main().

I am very curious how this work in terms of writing cross-platform codes. (I used the same fashion in my win32 code, it worked!! anyone explain the magic behind this please???)


Solution

  • What are the extern main and return main(__argc, __argv) doing?

    If you are compiling on a windows platform, SFML defines the WinMain entry point for you, and calls your main(int argc, char* argv[]) with __argc and __argv which are explained by the relevant documentation:

    The __argc global variable is a count of the number of command-line arguments passed to the program. __argv is a pointer to an array of single-byte-character or multi-byte-character strings that contain the program arguments.

    SFML does this, exacly such that that developers can use the standard main function even in a Win32 Application project, and thus keep a portable code. The comments in SFML/MainWin32.cpp explain this.