Artificial truth

The more you see, the less you believe.

[archives] [latest] | [homepage] | [atom/rss/twitter]

Fun with __attribute__
Mon 23 July 2012 — download

Did you know that gcc had a funny attribute mechanism that allows the developer to do some nice tricks ?


void my_function(int arg1) __attribute__((blablabla))

Please note the double underscore before and after, and the double parentheses.

Useful attributes


In general, functions are not inlined, unless gcc was told to optimize the code. This attribute will force functions declared inline to be inlined, even if no optimization level was specified.


Many functions (like math ones) have no other effect that returning a value. Using the const attribute on a function tell the compiler that for a given set of parameters, it will always return the same result. Doing so allows caching :)

constructor/destructor (priority)

The constructor attribute causes the function to be called before the main. The destructor one causes the function to be called after main () has completed or exit () has been called. Note that you can tweak their priority by passing a parameter to the argument :

void my_function(int arg1) __attribute__((constructor(1)));

deprecated (message)

The deprecated attribute issues a warning during compilation is the function is used.


On Intel 386, this will force the compiler to use the fastcall convention, by passing some arguments in registers instead of putting them on the stack.


Some standard library functions (abort, exit, ...) don't return. You can add this particularity to your functions too :

void my_function(void) __attribute__((noreturn))

void my_function(void){

    /* code */


optimize (argument)

The optimize attribute tells the compiler to use custom optimizations on this functions. Arguments can be numbers (optimization levels), or strings.

Variables ?

Of course, you can set attributes to variables :)

section ("name")

Usually, the compiler put objects in sections like data, or bss, tut you can place them in a custom section if you want :

int plop __attribute__((section("PLOP_HOUSE")));