Is there possibility to invoke other methods/instructions before main() when running the code [duplicate]

邮差的信 提交于 2020-01-06 04:37:09

问题


Possible Duplicate:
Can you print anything in C++, before entering into the main function?

Is there any possibility to run any other instructions before int main() is invoked?

int main(){cout<<"a";}

and before that call in main() there is call for cout<<"b"; somewhere before. Maybe this #define thing can help.


回答1:


You don't need a define. Just create a global object (in the same file) and its ctor (or anything else you use to initialize it, such as calling a function) will run before main is invoked.

Edit: likewise, those global objects will be destroyed after main exits, so their destructors will run at that time.




回答2:


Global objects are constructed before main() runs. So you can define a class, put your code in its constructor, and then declare a global instance of that class:

class temp
{
public:
    temp()
    {
        cout << "before main" << endl;
    }

    ~temp()
    {
       cout << "after main" << endl;
    }
};

temp t;

int main()
{
    cout << "in main" << endl;
    return 0;
}

Global variables are also initialized before main() runs. You can define a function that returns a value, then call that function and assign the value to a global variable in its declaration, like @jrok showed.

Some compilers also support a #pragma startup statement to execute a user-defined function at startup (and corresponding #pragma exit statement for shutdown):

void beforeMain()
{
    cout << "before main" << endl;
}
#pragma startup beforeMain

void afterMain()
{
    cout << "after main" << endl;
}
#pragma exit afterMain

int main()
{
    cout << "in main" << endl;
    return 0;
}


来源:https://stackoverflow.com/questions/14651731/is-there-possibility-to-invoke-other-methods-instructions-before-main-when-run

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!