在main函数前后执行的函数之 C语言
在gcc中,可以使用attribute關(guān)鍵字,聲明constructor和destructor,來(lái)指定了函數(shù)在main之前或之后運(yùn)行,代碼如下:
1 #include <stdio.h> 2 3 __attribute((constructor)) void before_main() 4 { 5 printf("%s/n",__FUNCTION__); 6 } 7 8 __attribute((destructor)) void after_main() 9 { 10 printf("%s/n",__FUNCTION__); 11 } 12 13 int main( int argc, char ** argv ) 14 { 15 printf("%s/n",__FUNCTION__); 16 return 0; 17 }當(dāng)然也可以指派多個(gè),而且在申明時(shí)?
void before() __attribute__((constructor));
void __attribute__((constructor)) before();
__attribute__((constructor)) void before();
這3種都是對(duì)的,__attribute__(())寫法比較隨意,當(dāng)一般推薦放在后面,當(dāng)然定義函數(shù)體的時(shí)候 __attribute__(()) 不能放在后面,推薦定義函數(shù)的時(shí)候一般不要使用,這就是為什么推薦第一種的原因,__attribute__屬性列表的用法還有還多,內(nèi)存對(duì)齊,函數(shù)格 式, 等等等等就不一一列舉了。man gcc 查找下 __attribute__可以發(fā)現(xiàn)這些,另標(biāo)準(zhǔn)庫(kù)和Linux內(nèi)核里面也有不少。
也可以一次指定多個(gè)屬性 如下:
1 void func(void) __attribute__((constructor destructor));?
在Windows的VC++中可以指定設(shè)定數(shù)據(jù)段來(lái)做,以實(shí)現(xiàn)同樣功能,如下:
1 #include <stdio.h> 2 3 int main(int argc, char ** argv) 4 { 5 printf("%s\n", "main"); 6 return 0; 7 } 8 9 int before() 10 { 11 printf("%s\n", "before"); 12 return 0; 13 } 14 15 int after() 16 { 17 printf("%s\n", "after"); 18 return 0; 19 } 20 21 typedef int func(); 22 23 #pragma data_seg(".CRT$XIU") 24 static func *before_function_array[] = { before }; 25 26 #pragma data_seg(".CRT$XPU") 27 static func *after_function_array[] = { after }; 28 29 #pragma data_seg()?
attribute還有個(gè)應(yīng)用, 就是增加函數(shù)別名(下面那個(gè)就不能是main了,要不就重復(fù)定義了):
# include <stdio.h> int main(int argc, char **argv) __attribute__((alias("LinuxMain")));int LinuxMain(int argc, char **argv) {printf("%s\n", __func__);return 0; }int main123(int argc, char **argv) {printf("%s\n", __func__);return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/marvin-notes/p/4432179.html
總結(jié)
以上是生活随笔為你收集整理的在main函数前后执行的函数之 C语言的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue3结合element-plus实现
- 下一篇: VSTO开发,转帖