Search code examples
c++program-entry-pointexternlinkage

Is it legal C++ to declare main as extern "C"?


Being a low-level programmer, I often work with the module startup code for executables, so I understand pretty well how code like "crt0" work. When writing C++ code, I've generally declared main as extern "C" to match what the C startup code is going to do to call main. I thus usually use this declaration for main (and wmain if specifically targeting Windows):

extern "C" int main(int argv, const char *const *argv)

extern "C" int __cdecl wmain(int argv, const wchar_t *const *argv)

Is it legal to use extern "C" on main? Also, is const char *const * legal for argv's type as opposed to char *[]?


Solution

  • The linkage is implementation defined (3.6.1p3):

    The linkage (3.5) of main is implementation-defined.

    Also, for your latter question, that is perfectly acceptable to have const char* const* (3.6.1p2):

    An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined.