GNU的擴展屬性之__attribute__的函數擴展屬性

   1、    在碰到這個問題以前,在學習linux的啓動時也知道main函數之前也會執行很多的初始化相關的程序,但是今天在一個應用程序中碰到了一個現象,就是函數的執行在main之前,廢話不多說先寫一個demo程序:

#include <stdio.h>


__attribute__((constructor)) void before(void)
{
	printf("run first\n");
}

__attribute__((destructor)) void after(void)
{
	printf("run after\n");
}

int main(void)
{
	printf("I am main function\n");
	
	return 0;
}

 編譯運行之後:打印的結果顯示:

run first
I am main function
run after

根據打印的結果我們可以看出來before函數在main函數之前先執行了,after函數在main函數之後執行。

之所以會有這個現象就是因爲before前面有個__attribute((constructor))__在修飾。__attribute((destructor))__在main函數之後執行。

2、如果在main之前還要執行很多的前置動作或者後續的處理動作,我們可以使用__attribute__((constructor(PRIORITY)))和__attribute__((destructor(PRIORITY))),PRIORITY的值是大於100的整數,可以從101開始,0-100之間的數值是系統使用的。

__attribute__((constructor(101))) void prec_proc1(void)

{
   printf("[%s %d]",__FUNCTION__,__LINE__);
}
__attribute__((destructor(101))) void end_proc1(void)

{
   printf("[%s %d]",__FUNCTION__,__LINE__);
}
__attribute__((constructor(102))) void prec_proc2(void)

{
   printf("[%s %d]",__FUNCTION__,__LINE__);
}
__attribute__((destructor(102))) void end_proc2(void)

{
   printf("[%s %d]",__FUNCTION__,__LINE__);
}

int main(void)
{
    printf("I am main function\n");
}

編譯之後運行結果如下:

[start_proc1 17]
[start_proc2 25]
I am main function
[end_proc2 29]
[end_proc1 21]
所以:前處理是按照優先級處理,後處理則是相反的。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章