__attribute__ in C

__attribute__ in C

__atrribute__ in C

Take a look at this code for example (in Cygwin master branch /winsup/cygwin/winsup.h)


__attribute__((constructor)) void fun1()
    printf("Hello "); 
__attribute__((destructor)) void fun2() 
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

Leave a Reply

Your email address will not be published. Required fields are marked *

eighteen − seven =

This site uses Akismet to reduce spam. Learn how your comment data is processed.