在 C 語言中在 main() 前後執行的函式


這裡我們將學習如何編寫一段程式碼,其中存在兩個函式,並且一個函式將在主函式之前執行,而另一個函式將在主函式之後執行。這些特性可用於在執行主函式之前執行一些啟動任務,以及在執行主函式之後執行一些清理任務。

要執行此任務,我們必須為這兩個函式指定屬性。當屬性為建構函式屬性時,它將在 main() 之前執行,而當屬性為解構函式型別時,它將在 main() 之後執行。

示例程式碼

#include<stdio.h>
void before_main() __attribute__((constructor));
void after_main() __attribute__((destructor));
void before_main() {
   printf("This is executed before main.
"); } void after_main() {    printf("This is executed after main."); } main() {    printf("Inside main
"); }

輸出

This is executed before main.
Inside main
This is executed after main.

更新於: 2019 年 7 月 30 日

3 千+次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告