\_\_attribute\_\_ in C
[ ]The content is recoverd from Wordpress Blog, for more details please check HERE
September 14, 2015
__atrribute__
in C The content is recoverd from Wordpress Blog, for more details please check HERE
Take a look at this code for example (in Cygwin master branch /winsup/cygwin/winsup.h)
#include<stdio.h>
\_\_attribute\_\_((constructor)) void fun1()
{
printf("Hello ");
}
\_\_attribute\_\_((destructor)) void fun2()
{
printf("Worldn");
}
int main(void)
{
return 0;
}
Then gcc xxx.c and then run the code it will print out “Hello World” ~
So why it works?
The code with constructor attribute run before main function and code with destructor attr run after main function
The __attribute__
can do more than above
Another usage of __attribute__
is to customize the section of a certain code , take a look at this example:
\_\_attributes\_\_((section(".my\_custom\_section"))) int main(void) { return 0; }
Then compile the code and run readelf tool to check the section in the code:
$ readelf -S a.out
You can see a section called my_custom_section and with AX acess(alloc + executable)
This proves that we can use __attribute__
to customize the section
wine, 计算机系统原理 C. Linux, kernel, Laravel, PHP, Python, Shell, Web, wine
Historical Comments
Post navigation ————— NEXT
计算机网络的体系结构(Computer Network Architecture) PREVIOUS Linking