Question

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 *[]?

Was it helpful?

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.

OTHER TIPS

extern "C" only tells the C++ compiler specifically to NOT decorate or use name wrangling on generated function labels.

Yes, both are legal.

The standard blesses two forms of main:

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

These forms are what any implementation must recognize. Everything else is your implementation being easy with your code and letting you be creative. It is not illegal, as the standard specifically allows it to recognize other forms of main.

The startup code is normally written in a way that allows it to call main having no linkage declaration, because that's how the standard says main should be. The compiler usually treats main specially as having C linkage, as allowed by the standard, so that's how the startup code declares it. This is of no interest to a normal programmer. He just needs to follow the standard.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top