我在學習Python的時候,對于main的判斷有一定的了解。后來,當我學習C語言時,我發現,其實這一切都是互通的,下面就各位講解下C語言中如何在main函數開始前執行函數。
在gcc中,可以使用attribute關鍵字,聲明constructor和destructor,代碼如下:
?
__attribute((constructor)) void before_main()
{
?printf("%s/n",__FUNCTION__);
}
__attribute((destructor)) void after_main()
{
?printf("%s/n",__FUNCTION__);
}
int main( int argc, char ** argv )
{
?printf("%s/n",__FUNCTION__);
?return 0;
}
?vc不支持attribute關鍵字,在vc中,可以使用如下方法:
?
?
?
int
main( int argc, char ** argv )
{
??????? printf("%s/n",__FUNCTION__);
??????? return 0;
}
int before_main()
{
??????? printf("%s/n",__FUNCTION__);
??????? return 0;
}
int after_main()
{
??????? printf("%s/n",__FUNCTION__);
??????? return 0;
}
typedef int func();
#pragma data_seg(".CRT$XIU")
static func * before[] = { before_main };
#pragma data_seg(".CRT$XPU")
static func * after[] = { after_main };
#pragma data_seg()
編譯執行,上述兩段代碼的結果均為:
?
before_main
main
after_main
可以在main前后調用多個函數,在gcc下使用attribute聲明多個constructor、destructor,vc下在before、after數組中添加多個函數指針。
以上便是C語言中如何在main函數開始前執行函數的所有知識點,如果你想更深入的了解C語言,那可以繼續關注武林技術頻道,武林小編會每日進行更新。
新聞熱點
疑難解答
圖片精選