C 中的 attribute((constructor)) 和 attribute((destructor)) 語法在 tutorials point 中是如何使用的?


我們將瞭解如何編寫一個程式碼,其中有兩個函式,一個函式將在主函式之前執行,另一個函式將在主函式之後執行。這些特性用於在執行主函式之前執行一些啟動任務,並在執行主函式之後執行一些清理任務。

為此,我們必須為這兩個函式賦予屬性。屬性為建構函式屬性時,它將在 main() 之前執行,屬性為解構函式型別時,它將 main() 之後執行。

我們使用 GCC 函式。該函式為 __attribute__(). 在本例中,我們使用兩個不同的選項。使用 __attribute__() 函式的建構函式和解構函式。語法 __attribute__((constructor)) 用於在程式啟動時執行函式。而語法 __attribute__((destructor)) 用於在 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

2K+ 檢視

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.