Why the call to main () is not allowed in C ++

C++03 3.6.1.3 : The main function should not be used (3.2) inside the program ....

I wonder why this rule exists ... Does anyone know of any system / implementation where this would be a problem if main were used?

PS 1. I know the definition of the term used . 2. I know that there are simple workarounds, for example, calling one MyMain () from main () and using MyMain (). 3. We are talking about realities of the real world that would have a problem if there were no restrictions there. Thank!

+14
c ++ main
Nov 10 '10 at
source share
3 answers

In addition to the other answers: the C ++ specification ensures that all static initialization occurs before main is called.

If the code could call main, then some object with static areas could call main, in which case the fundamental guarantee is violated.

The specification cannot say that "objects with a non-stationary region should not call main ()," because many objects are not written specifically for instantiation in a static region. He also cannot say that constructors should not call main () - because it is very difficult to test and prove that the constructor does not call a method, calling a method that can sometimes call main ().

+33
Nov 10 '10 at
source share

I would suggest that this saves the freedom to implement the main prefix with code for building global and static data, accepts any parameters defining the arguments of the environment and command line, and compares them with the argc / argv / env conventions in C ++, constructs the corresponding stack and exception framework for the application to run, etc. Note that not all environments can allow an executable image to have any other character designated as initialization code, which must be run before main() .

Similarly, a cleanup code can be added to main() along with an OS call with some mapping from the 0 / zero-free C and C ++ convention with the actual success / failure values ​​used by that particular OS.

Therefore, calling main from another place may try to re-initialize the application framework or force an unintended exit to the OS - it sounds disastrous for me.

+16
Nov 10 2018-10-11
source share

C ++ main() is a strange little function that has different syntax for handling exceptions, should not return a value, even if it should be defined as returning an int, etc. I don’t know, it affects any real implementation, but I would suggest that there is a limitation to give the compiler authors some latitude in the way they implement main() .

+4
Nov 10 2018-10-11
source share



All Articles