【问题标题】:Is there possibility to invoke other methods/instructions before main() when running the code [duplicate]运行代码时是否有可能在 main() 之前调用其他方法/指令[重复]
【发布时间】:2013-01-17 02:03:56
【问题描述】:

可能重复:
Can you print anything in C++, before entering into the main function?

在调用 int main() 之前是否有可能运行任何其他指令?

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

在 main() 调用之前,调用 cout

【问题讨论】:

  • bool f() { cout &lt;&lt; "before main"; return true; } bool dummy = f(); int main(){ cout&lt;&lt;"main"; }
  • 当然有,google一下。
  • 是的。其实你甚至可以在main之前退出程序:)
  • 我觉得我一直在关注这一点,直到 “this #define thing”。那么……嗯?
  • @chris,你的意思是当你的 main 代码运行时进程终止了?对我来说听起来像是一个错误:p

标签: c++ invoke main


【解决方案1】:

全局对象在 main() 运行之前构建。所以你可以定义一个类,把你的代码放在它的构造函数中,然后声明一个该类的全局实例:

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

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

temp t;

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

全局变量也在 main() 运行之前初始化。您可以定义一个返回值的函数,然后调用该函数并将值分配给其声明中的全局变量,就像 @jrok 显示的那样。

一些编译器还支持#pragma startup 语句在启动时执行用户定义的函数(以及相应的#pragma exit 语句用于关闭):

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;
}

【讨论】:

  • 只是全局并不能确保在 main 执行之前创建/初始化对象。它必须与 main 在同一个翻译单元中,以确保在调用 main 之前创建它。
【解决方案2】:

您不需要define。只需创建一个全局对象(在同一个文件中),它的 ctor(或用于初始化它的任何其他东西,例如调用函数)将在 main 被调用之前运行。

编辑:同样,那些全局对象将在 main 退出后被销毁,因此它们的析构函数将在那时运行。

【讨论】:

  • 工作得很好。我会尽快接受。是否有可能在 main() 之后运行一些东西?
  • @RobertKilar,析构函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 1970-01-01
相关资源
最近更新 更多