日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

在main函数前后执行的函数之 C语言

發(fā)布時(shí)間:2023/12/10 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在main函数前后执行的函数之 C语言 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

在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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。