Title: Fun with __attribute__
Date: 2012-07-23 18:12

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

Syntax
======

    :::c
    void my_function(int arg1) __attribute__((blablabla))
    __attribute__((blublublu));

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

Useful attributes
=================

always_inline
--------------

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.

const
-----

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 :

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

deprecated (message)
--------------------

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

fastcall
--------

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.

noreturn
--------

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

    :::c
    void my_function(void) __attribute__((noreturn))

    void my_function(void){

        /* code */

        exit(1);
    }

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 :

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

Sources
=======

-   [gcc's documentation][]

  [*fastcall*]: http://ohse.de/uwe/articles/gcc-attributes.html#func-fastcall
    "fastcall"
  [attributes]: http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html#Variable-Attributes
  [gcc's documentation]: http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes
