1. 程式人生 > 其它 >在main函式前面執行的函式

在main函式前面執行的函式

技術標籤:C/C++

/************************************************************************/
/* 
1.使用attribute關鍵字,宣告constructor和destructor函式(gcc中,注意:vc中不支援attribute)
2.通過段名稱“.CRTXIU”,“.CRTXCU”把函式放在“C/C++初始化函式表”中
3.利用全域性物件的建構函式會在main函式之前執行的特點

*/
/************************************************************************/
/************************************************************************/ /* C++ 中的_onexit() 函式:這個函式可以實現在main主函式執行完畢之後,才執行的程式碼。 (1)使用格式:_onexit(int fun()) ,其中函式fun()必須是帶有int型別返回值的無引數函式; (2)_onexit() 包含在標頭檔案cstdlib中,cstdlib為c語言中的庫函式; (3)無論函式_onexit() 放到main中任意位置,它都是最後執行。 (4) _onexit(): 多個onexit() 函式就是寫在mian前面的是最後執行。 */
/************************************************************************/ #include <iostream> using namespace std; int func1() { cout << "this is func1() " << endl; return 0; } int func2() { cout << "this is func2() " << endl; return 0; } int func3
() { cout << "this is func3() " << endl; return 0; } typedef int func(); #pragma data_seg(".CRT$XIU") //用#pragma data_seg建立一個新的資料段並定義共享資料 func* myfunc1 = func1; //XIU 是最先執行的, 然後是全域性物件的建構函式, 然後是XCU執行, 然後是main執行,最後全域性物件的解構函式 #pragma data_seg(".CRT$XCU") func* myfunc2 = func2; //#pragma data_seg() // 3. 全域性物件的建構函式會在main 函式之前執行 class MyClass { public: MyClass() { cout << "MyClass constructor function! " << endl; } ~MyClass() { cout << "~MyClass destructor function! " << endl; } }; MyClass test; // 利用全域性物件的建構函式會在main函式之前執行的特點。 int main() { //_onexit(func1); // 寫在main函式中的 最後執行的函式,無論什麼位置, 如果有多個,則寫在前面的最後執行。 cout << "this is main function " << endl; //_onexit(func2); //_onexit(func3); return 0; }

在這裡插入圖片描述


C++ 中的_onexit() 函式:這個函式可以實現在main主函式執行完畢之後,才執行的程式碼。
(1)使用格式:_onexit(int fun()) ,其中函式fun()必須是帶有int型別返回值的無引數函式;
(2)_onexit() 包含在標頭檔案cstdlib中,cstdlib為c語言中的庫函式;
(3)無論函式_onexit() 放到main中任意位置,它都是最後執行。
(4) _onexit(): 如果有多個onexit() 函式,就是寫在mian前面的是最後執行。

/************************************************************************/
/* 
C++ 中的_onexit() 函式:這個函式可以實現在main主函式執行完畢之後,才執行的程式碼。
(1)使用格式:_onexit(int fun()) ,其中函式fun()必須是帶有int型別返回值的無引數函式;
(2)_onexit() 包含在標頭檔案cstdlib中,cstdlib為c語言中的庫函式;
(3)無論函式_onexit() 放到main中任意位置,它都是最後執行。
(4) _onexit(): 多個onexit() 函式就是寫在mian前面的是最後執行。
*/
/************************************************************************/

#include <iostream>

using namespace std;

int func1()
{
	cout << "this is func1() " << endl;
	return 0;
}

int func2()
{
	cout << "this is func2() " << endl;
	return 0;
}

int func3()
{
	cout << "this is func3() " << endl;
	return 0;
}
// 3. 全域性物件的建構函式會在main 函式之前執行 
class MyClass {
public:
	MyClass()
	{
		cout << "MyClass constructor function! " << endl;
	}
	~MyClass()
	{
		cout << "~MyClass destructor function! " << endl;
	}
};

MyClass test;    // 利用全域性物件的建構函式會在main函式之前執行的特點。

int main()
{
	_onexit(func1);  // 寫在main函式中的 最後執行的函式,無論什麼位置, 如果有多個,則寫在前面的最後執行。
	cout << "this is main function " << endl;
	_onexit(func2);
	_onexit(func3);
	return 0;
}

在這裡插入圖片描述