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 on all targets: noreturn
, noinline
, always_inline
, pure
, const
, format
,format_arg
, no_instrument_function
, section
, constructor
, destructor
, used
, unused
, deprecated
, weak
, malloc
, and alias
. Several other attributes are defined for functions on particular target systems. Other attributes, including section
are supported for variables declarations (see Variable Attributes) and for types (see Type Attributes).
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
.
See Attribute Syntax, for details of the exact syntax for using attributes.
noreturn
abort
and exit
, cannot return. GCC knows this automatically. Some programs define their own functions that never return. You can declare them noreturn
to tell the compiler this fact. For example,
void fatal () __attribute__ ((noreturn));
void
fatal (...)
{
... /* Print error message. */ ...
exit (1);
}
The noreturn
keyword tells the compiler to assume that fatal
cannot return. It can then optimize without regard to what would happen if fatal
ever did return. This makes slightly better code. More importantly, it helps avoid spurious warnings of uninitialized variables.
Do not assume that registers saved by the calling function are restored before calling the noreturn
function.
It does not make sense for a noreturn
function to have a return type other than void
.
The attribute noreturn
is not implemented in GCC versions earlier than 2.5. An alternative way to declare that a function does not return, which works in the current version and in some older versions, is as follows:
typedef void voidfn ();
volatile voidfn fatal;
noinline
always_inline
pure
pure
. For example,
int square (int) __attribute__ ((pure));
says that the hypothetical function square
is safe to call fewer times than the program says.
Some of common examples of pure functions are strlen
or memcmp
. Interesting non-pure functions are functions with infinite loops or those depending on volatile memory or other system resource, that may change between two consecutive calls (such as feof
in a multithreading environment).
The attribute pure
is not implemented in GCC versions earlier than 2.96.
const
pure
attribute above, since function is not allowed to read global memory.
Note that a function that has pointer arguments and examines the data pointed to must not be declared const
. Likewise, a function that calls a non-const
function usually must not be const
. It does not make sense for a const
function to return void
.
The attribute const
is not implemented in GCC versions earlier than 2.5. An alternative way to declare that a function has no side effects, which works in the current version and in some older versions, is as follows:
typedef int intfn ();
extern const intfn square;
This approach does not work in GNU C++ from 2.6.0 on, since the language specifies that the const
must be attached to the return value.
format (
archetype,
string-index,
first-to-check)
format
attribute specifies that a function takes printf
, scanf
, strftime
or strfmon
style arguments which should be type-checked against a format string. For example, the declaration:
extern int
my_printf (void *my_object, const char *my_format, ...)
__attribute__ ((format (printf, 2, 3)));
causes the compiler to check the arguments in calls to my_printf
for consistency with the printf
style format string argument my_format
.
The parameter archetype determines how the format string is interpreted, and should be printf
, scanf
, strftime
or strfmon
. (You can also use __printf__
,__scanf__
, __strftime__
or __strfmon__
.) The parameter string-index specifies which argument is the format string argument (starting from 1), while first-to-check is the number of the first argument to check against the format string. For functions where the arguments are not available to be checked (such as vprintf
), specify the third parameter as zero. In this case the compiler only checks the format string for consistency. For strftime
formats, the third parameter is required to be zero.
In the example above, the format string (my_format
) is the second argument of the function my_print
, and the arguments to check start with the third argument, so the correct parameters for the format attribute are 2 and 3.
The format
attribute allows you to identify your own functions which take format strings as arguments, so that GCC can check the calls to these functions for errors. The compiler always (unless -ffreestanding
is used) checks formats for the standard library functions printf
, fprintf
, sprintf
,scanf
, fscanf
, sscanf
, strftime
, vprintf
, vfprintf
and vsprintf
whenever such warnings are requested (using -Wformat
), so there is no need to modify the header file stdio.h
. In C99 mode, the functions snprintf
, vsnprintf
, vscanf
, vfscanf
and vsscanf
are also checked. Except in strictly conforming C standard modes, the X/Open function strfmon
is also checked as are printf_unlocked
and fprintf_unlocked
. See Options Controlling C Dialect.
format_arg (
string-index)
format_arg
attribute specifies that a function takes a format string for a printf
, scanf
, strftime
or strfmon
style function and modifies it (for example, to translate it into another language), so the result can be passed to a printf
, scanf
, strftime
or strfmon
style function (with the remaining arguments to the format function the same as they would have been for the unmodified string). For example, the declaration:
extern char *
my_dgettext (char *my_domain, const char *my_format)
__attribute__ ((format_arg (2)));
causes the compiler to check the arguments in calls to a printf
, scanf
, strftime
or strfmon
type function, whose format string argument is a call to themy_dgettext
function, for consistency with the format string argument my_format
. If the format_arg
attribute had not been specified, all the compiler could tell in such calls to format functions would be that the format string argument is not constant; this would generate a warning when -Wformat-nonliteral
is used, but the calls could not be checked without the attribute.
The parameter string-index specifies which argument is the format string argument (starting from 1).
The format-arg
attribute allows you to identify your own functions which modify format strings, so that GCC can check the calls to printf
, scanf
, strftime
or strfmon
type function whose operands are a call to one of your own function. The compiler always treats gettext
, dgettext
, and dcgettext
in this manner except when strict ISO C support is requested by -ansi
or an appropriate -std
option, or -ffreestanding
is used. See Options Controlling C Dialect.
no_instrument_function
-finstrument-functions
is given, profiling function calls will be generated at entry and exit of most user-compiled functions. Functions with this attribute will not be so instrumented. section ("
section-name")
text
section. Sometimes, however, you need additional sections, or you need certain particular functions to appear in special sections. The section
attribute specifies that a function lives in a particular section. For example, the declaration:
extern void foobar (void) __attribute__ ((section ("bar")));
puts the function foobar
in the bar
section.
Some file formats do not support arbitrary sections so the section
attribute is not available on all platforms. If you need to map the entire contents of a module to a particular section, consider using the facilities of the linker instead.
constructor
destructor
constructor
attribute causes the function to be called automatically before execution enters main ()
. Similarly, the destructor
attribute causes the function to be called automatically after main ()
has completed or exit ()
has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.
These attributes are not currently implemented for Objective-C.
unused
used
deprecated
deprecated
attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead. Note that the warnings only occurs for uses:
int old_fn () __attribute__ ((deprecated));
int old_fn ();
int (*fn_ptr)() = old_fn;
results in a warning on line 3 but not line 2.
The deprecated
attribute can also be used for variables and types (see Variable Attributes, see Type Attributes.)
weak
weak
attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations. Weak symbols are supported for ELF targets, and also for a.out targets when using the GNU assembler and linker. malloc
malloc
attribute is used to tell the compiler that a function may be treated as if it were the malloc function. The compiler assumes that calls to malloc result in a pointers that cannot alias anything. This will often improve optimization. alias ("
target")
alias
attribute causes the declaration to be emitted as an alias for another symbol, which must be specified. For instance,
void __f () { /* do something */; }
void f () __attribute__ ((weak, alias ("__f")));
declares f
to be a weak alias for __f
. In C++, the mangled name for the target must be used.
Not all target machines support this attribute.
regparm (
number)
regparm
attribute causes the compiler to pass up to number integer arguments in registers EAX, EDX, and ECX instead of on the stack. Functions that take a variable number of arguments will continue to be passed all of their arguments on the stack. stdcall
stdcall
attribute causes the compiler to assume that the called function will pop off the stack space used to pass arguments, unless it takes a variable number of arguments.
The PowerPC compiler for Windows NT currently ignores the stdcall
attribute.
cdecl
cdecl
attribute causes the compiler to assume that the calling function will pop off the stack space used to pass arguments. This is useful to override the effects of the -mrtd
switch.
The PowerPC compiler for Windows NT currently ignores the cdecl
attribute.
longcall
longcall
attribute causes the compiler to always call the function via a pointer, so that functions which reside further than 64 megabytes (67,108,864 bytes) from the current location can be called. long_call/short_call
-mlong-calls
(see ARM Options) command line switch and #pragma long_calls
settings. The long_call
attribute causes the compiler to always call the function by first loading its address into a register and then using the contents of that register. The short_call
attribute always places the offset to the function from the call site into the BL
instruction directly. dllimport
dllimport
attribute causes the compiler to call the function via a global pointer to the function pointer that is set up by the Windows NT dll library. The pointer name is formed by combining __imp_
and the function name. dllexport
dllexport
attribute causes the compiler to provide a global pointer to the function pointer, so that it can be called with the dllimport
attribute. The pointer name is formed by combining __imp_
and the function name. exception (
except-func [,
except-arg])
exception
attribute causes the compiler to modify the structured exception table entry it emits for the declared function. The string or identifier except-func is placed in the third entry of the structured exception table. It represents a function, which is called by the exception handling mechanism if an exception occurs. If it was specified, the string or identifier except-arg is placed in the fourth entry of the structured exception table. function_vector
You must use GAS and GLD from GNU binutils version 2.7 or later for this attribute to work correctly.
interrupt
Note, interrupt handlers for the H8/300, H8/300H and SH processors can be specified via the interrupt_handler
attribute.
Note, on the AVR interrupts will be enabled inside the function.
Note, for the ARM you can specify the kind of interrupt to be handled by adding an optional parameter to the interrupt attribute like this:
void f () __attribute__ ((interrupt ("IRQ")));
Permissible values for this parameter are: IRQ, FIQ, SWI, ABORT and UNDEF.
interrupt_handler
sp_switch
interrupt_handler
function should switch to an alternate stack. It expects a string argument that names a global variable holding the address of the alternate stack.
void *alt_stack;
void f () __attribute__ ((interrupt_handler,
sp_switch ("alt_stack")));
trap_exit
interrupt_handle
to return using trapa
instead of rte
. This attribute expects an integer argument specifying the trap number to be used. eightbit_data
You must use GAS and GLD from GNU binutils version 2.7 or later for this attribute to work correctly.
tiny_data
signal
naked
model (
model-name)
small
, medium
, or large
, representing each of the code models.
Small model objects live in the lower 16MB of memory (so that their addresses can be loaded with the ld24
instruction), and are callable with the bl
instruction.
Medium model objects may live anywhere in the 32-bit address space (the compiler will generate seth/add3
instructions to load their addresses), and are callable with the bl
instruction.
Large model objects may live anywhere in the 32-bit address space (the compiler will generate seth/add3
instructions to load their addresses), and may not be reachable with the bl
instruction (the compiler will generate the much slower seth/add3/jl
instruction sequence).
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.
#pragma
commands from a macro.#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. See Miscellaneous Preprocessing Directives.
====
http://gcc.gnu.org/onlinedocs/gcc-3.1/gcc/Function-Attributes.html#Function%20Attributes