C++ 是否存在一个在main()主函数之前就执行的函数? 这个可以有!

 一般地,大家都知道的常规:

C/C++ 程序是从main()函数开始执行的
main()函数有参数和返回值
main()函数是操作系统调用的函数
操作系统总是将main()函数作为应用程序的开始
操作系统将main()函数的返回值作为程序的退出状态

那究竟有否能在main()主函数之前执行的函数呢?

答案:有! 

有些编译器支持关键字 attribute,能指定在 main 之前 (constructor) 、main 之后 (destructor) 分别执行一个函数。

__attribute__((constructor)) void init()    // 在main()之前工作
__attribute__((destructor))  void exit()    // 在main()之后工作

但不是所有的编译器都支持相关功能关键字扩展,以下代码可在TDM-GCC 4.9.2 或 gcc7.5.0 上通过无错无警告编译:

#include <iostream>
using namespace std;

int i;

__attribute__((constructor)) void init()
{
    cout << __FUNCTION__ << endl;
    cout << "构造函数:初始化工作" << endl;

    i = 323;
}

__attribute__((destructor)) void exit()
{
    cout << __FUNCTION__ << endl;
    cout << "析构函数:退出程序 bye!" << endl;
}

int main()
{
    cout << __FUNCTION__ << endl;
    cout << "main()主函数:执行事务\n";
    cout << "输出变量 i = " << i << endl;
    
    return 0;
}

执行结果:

init
构造函数:初始化工作
main
main()主函数:执行事务
输出变量 i = 323
exit
析构函数:退出程序 bye!

--------------------------------
Process exited after 0.4433 seconds with return value 0
请按任意键继续. . .

参考资料:

  《main 函数与命令行参数

猜你喜欢

转载自blog.csdn.net/boysoft2002/article/details/114278061