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.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP