Specifying Attributes of Functions

Previous GNU C Language Extensions Next

In GNU C, you declare certain things about functions called in your program which help the compiler optimize function calls and check your code more carefully.

The keyword __attribute__ allows you to specify special attributes when making a declaration. This keyword is followed by an attribute specification inside double parentheses. The following attributes are currently defined for functions:

Other attributes are supported for variable declarations (see Variable Attributes) and for types (see Type Attributes).

TIGCC also defines the macros CALLBACK, __ATTR_TIOS__, __ATTR_TIOS_NORETURN__, __ATTR_TIOS_CALLBACK__, __ATTR_GCC__, __ATTR_LIB_C__, __ATTR_LIB_ASM__, __ATTR_LIB_ASM_NORETURN__, __ATTR_LIB_CALLBACK_C__, and __ATTR_LIB_CALLBACK_ASM__. They are useful for specifying default attributes for a specific class of functions. You only need to use them when you define a callback function. For example, the callback function type compare_t needs the attributes specified by __ATTR_LIB_CALLBACK_C__, i.e. the attributes required by a callback function for a library function written in C. Since this is too inconvenient for the user, all three callback attributes have been made equal, and we have defined a single CALLBACK macro.

You may also specify attributes with __ preceding and following each keyword. This allows you to use them in header files without being concerned about a possible macro of the same name. For example, you may use __noreturn__ instead of noreturn. For example, as malloc is defined as a macro in the TIGCC Library, always use __malloc__ instead of malloc.

See Attribute Syntax for details of the exact syntax for using attributes.

You can specify multiple attributes in a declaration by separating them by commas within the double parentheses or by immediately following an attribute declaration with another attribute declaration.

Some people object to the __attribute__ feature, suggesting that ISO C's #pragma should be used instead. At the time __attribute__ was designed, there were two reasons for not doing this.

  1. It is impossible to generate #pragma commands from a macro.

  2. There is no telling what the same #pragma might mean in another compiler.
These two reasons applied to almost any application that might have been proposed for #pragma. It was basically a mistake to use #pragma for anything.

The ISO C99 standard includes _Pragma, which now allows pragmas to be generated from macros. In addition, a #pragma GCC namespace is now in use for GCC-specific pragmas. However, it has been found convenient to use __attribute__ to achieve a natural attachment of attributes to their corresponding declarations, whereas #pragma GCC is of use for constructs that do not naturally form part of the grammar.