Why main() in C++ cannot be inlined?
In C++ it is not legal to call the main function in your code, so there'd be no way it could ever be inlined.
Because the standard says so:
[2003: 3.6.1/3]
: The function main shall not be used (3.2) within a program. The linkage (3.5) of main is implementation-defined. A program that declares main to be inline or static is ill-formed. The name main is not otherwise reserved. [Example: member functions, classes, and enumerations can be called main, as can entities in other namespaces. ]
And why does it say so? Because it's trying to leave as much about the implementation of main
to the individual .. well, implementation .. as is possible, and doesn't want to limit implementations by requiring that inline
be valid here when it arguably has no practical benefit.
My friend on the committee confirmed this:
There's no reason why an
inline
main()
wouldn't work, per se. [..] I could have a C++ interpreter that can invoke inlinedmain()
. [..] [But]inline
/static
main()
are forbidden in order to hopefully avoid confusion. I find it hard to imagine that the rationale would be anything additional to what's already been said in [this Q&A].
BTW, don't confuse the inline
hint keyword with actually inlining functions. You can mark a function inline
and it may not be physically inlined.
So, even if it were true that main
"cannot be inlined" (and strictly speaking it is not true, though inlining main
would be rather awkward and pointless as explained in other answers), it could theoretically still support the inline
hint keyword just fine.
It doesn't for the reason stated above, and in litb's answer: it would complicate matters for no real benefit.
The C runtime library needs to find this symbol in order to "know" which function to run.
You cannot directly call main() (it's forbidden in c++), so there is no point of inlining it.
Usually main()
is called from systems init()
function. Thus, it is needed that there can be exactly one definition for main()
.
Now, if we can inline
the main()
function and include in a header file then, for every translation unit there will be different definition for main()
. Which is not allowed. You can declare main()
in a namespace
and inline
it. But not the global main()
.