C語言中如何在main函數開始前執行函數
在gcc中,可以使用attribute關鍵字,聲明constructor和destructor,代碼如下:
- #include <stdio.h>
- __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中,可以使用如下方法:
- #include <stdio.h>
- 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數組中添加多個函數指針。
最後更新:2017-04-03 19:13:18