Multi-Play YY voice interview question: How to do before the main () function in C + +?

Source: Internet
Author: User
Tags terminates

Multi-Play YY voice interview question: How to do before the main () function in C + +?

The first response to the main () function is the start of all function execution. But the question is, how does the main () function execute before it executes?

The Theapp object of the C**app class is associated with MFC, and the order of execution is preceded by the main function. The reason is the same, Shun Li pushed, can think: if the main function before declaring a global object of a class . Then its execution order, depending on the lifetime and scope of the global object, is definitely preceded by the main function.

Examples are as follows:

Class Simpleclass{public:       simpleclass ()       {              cout << "Simpleclass constructor ..." << Endl;  Step2       }}; Simpleclass g_objectsimple;         Step1 Global Object int _tmain (int argc, _tchar* argv[])  //step3{       return 0; Single-step debugging to see the order of execution Step1, Step2, Step3.

With global objects in mind, the scope of static objects is further considered. The above example is further expanded as follows:

Class Simpleclass{public:       simpleclass ()       {              cout << "Simpleclass constructor ..." << Endl;       Step2        }};class simpleclasstwo{public:       static Simpleclass m_ssimpleclass;}; Simpleclass Simpleclasstwo::m_ssimpleclass = Simpleclass (); Step1 static object int _tmain (int argc, _tchar* argv[])                        //step3{        return 0; Single-step debugging to see the order of execution Step1, Step2, Step3.

At this point, we can conclude that the global object defined before the main () function and the constructor of the static object are executed before the main () function.

Consider further, since the constructor of the global, static object can be executed before the main () function. So is there a function that executes after the main () function?

Yes, the OnExit function. The prototype is as follows:

_onexit_t _onexit (

_onexit_t function

);

_onexit_t_m _onexit_m (

_onexit_t_m function

);

Explanation: The _onexit function is passed, the address of a function (function) to being called when the program terminates normally. Successive calls to _onexit create a register of functions that is executed in LIFO (last-in-first-out) Order. The functions passed to _onexit cannot take parameters.

Core points:

1) Execution period-when the execution of the program terminates;

2) Pass the parameter--the address of the function, i.e. the function pointer;

3) Order of execution-LIFO first.

_onexit is a Microsoft extension. For ANSI portability, use atexit. The _onexit_m version of the function is to mixed mode use.

OnExit is an extended version of Microsoft, and the standard C + + application is atexit.

"MSDN" Example:

#include <stdlib.h> #include <stdio.h>/* prototypes */int fn1 (void), fn2 (void), fn3 (void), fn4 (void), int Main (void) {      _onexit (fn1);      _onexit (FN2);      _onexit (FN3);      _onexit (FN4);      printf ("This is executed first.\n");} int fn1 () {      printf ("next.\n");      return 0;} int fn2 () {      printf ("executed");      return 0;} int Fn3 () {      printf ("is");      return 0;} int Fn4 () {      printf ("this");      return 0;}

The results of the implementation are as follows:

Obviously, the read program can see that the main () function executes and then executes the onexit () function.

Is there any other special situation? Continue to explore, update ...

2013-4-23 Update

Add: How does the Console interface application start?

Taking the Windows platform as an example, when you create an application project with MicrosoftVisual Studio, the integrated development environment sets up various connection switches that allow the linker to embed the correct type of subsystem into the resulting executable (executable) file. For the console interface application, the switch for this linker is/subsystem:console.

When the user launches the application, the operating system loader (loader) examines the file header of the executable image and obtains the subsystem value. If the subsystem value is/subsystem:console as shown, the loader automatically ensures that the command character starts the program with a text console window available. In addition, a new window is created if necessary, such as when you start the Cui program from Resource Manager.

When you connect an executable file, the linker chooses the correct C + + runtime startup function. If/subsystem:console is specified, the following steps are performed:

All the things that are done by all the C + + runtime startup functions are basically the same, except that 1 of them handle the type of string (ANSI string or Unicode string), and the difference is 2 in which entry point function they call.

The purpose of the source code startup function for Visual C + + 's own C + + runtime is briefly summarized as follows:

1) Get a pointer to the complete command line of the new process;

2) Gets a pointer to the environment variable of the new process;

3) Initialize the global variables of the C + + runtime library.

4) initializes the heap used by the C run-time library memory allocation functions (malloc and calloc) and other underlying I/O routines.

5) Call the constructors of all global and static C + + class objects .

The 5th article also explains why the constructor of the global, static variable is run before the main () function.

When the entry point function returns, the startup function calls the C run-Library function exit, passing it the return value (Nmainretval). The Exit function performs the following tasks:

1) Call the _onexit function all calls to any of the functions registered;

2) call destructors for all global and static C + + class objects;

3) in debug builds, if the _CRTDBG_LEAK_CHECK_DF flag is set, a memory leak report is generated by calling the _CrtDumpMemoryLeaks function.

4) Call the operating system's ExitProcess function and pass it to the Nmainretval. This causes the operating system to kill our process and set its exit code.

The exit () function executes in order of 1), 2), 3), 4).

The following combination of the above procedures verifies the order in which the Exit function is executed.

First, the Global object constructor, then executes the main function print statement, then executes the _onexit registration function, and finally executes the global object destructor.

#include <stdlib.h> #include <stdio.h> class Simpleclass{public:       simpleclass ()       {              cout< < "Simpleclass constructor ..." << Endl;       }       ~simpleclass ()       {              cout<< "~simpleclass destructor:" << Endl;       }}; simpleclass g_objectsimple;      1 Global Object/* prototypes */int fn1 (void), fn2 (void), fn3 (void), fn4 (void); int main (void) {       _onexit (fn1);       _onexit (FN2);       _onexit (FN3);       _onexit (FN4);       printf ("This is executed first.\n");} int fn1 () {       printf ("next.\n");       Return0;} int fn2 () {       printf ("executed");       Return0;} int Fn3 () {       printf ("is");       Return0;} int Fn4 () {       printf ("this");       Return0;}


Ming Yi World

Reprint please indicate source, original address: http://blog.csdn.net/laoyang360/article/details/8820501

If you feel this article is helpful, please click on the ' top ' support, your support is I insist on writing the most power, thank you!

Multi-Play YY voice interview question: How to do before the main () function in C + +?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.