The following attributes are supported on most targets.
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")));
defines ‘f’ to be a weak alias for ‘__f’. In C++, the mangled name for the target must be used. It is an error if ‘__f’ is not defined in the same translation unit.
This attribute requires assembler and object file support,
and may not be available on all targets.
aligned (
alignment)
You cannot use this attribute to decrease the alignment of a function, only to increase it. However, when you explicitly specify a function alignment this overrides the effect of the -falign-functions (see Optimize Options) option for this function.
Note that the effectiveness of aligned
attributes may be
limited by inherent limitations in your linker. On many systems, the
linker is only able to arrange for functions to be aligned up to a
certain maximum alignment. (For some linkers, the maximum supported
alignment may be very very small.) See your linker documentation for
further information.
The aligned
attribute can also be used for variables and fields
(see Variable Attributes.)
alloc_align
alloc_align
attribute is used to tell the compiler that the
function return value points to memory, where the returned pointer minimum
alignment is given by one of the functions parameters. GCC uses this
information to improve pointer alignment analysis.
The function parameter denoting the allocated alignment is specified by one integer argument, whose number is the argument of the attribute. Argument numbering starts at one.
For instance,
void* my_memalign(size_t, size_t) __attribute__((alloc_align(1)))
declares that my_memalign
returns memory with minimum alignment
given by parameter 1.
alloc_size
alloc_size
attribute is used to tell the compiler that the
function return value points to memory, where the size is given by
one or two of the functions parameters. GCC uses this
information to improve the correctness of __builtin_object_size
.
The function parameter(s) denoting the allocated size are specified by one or two integer arguments supplied to the attribute. The allocated size is either the value of the single function argument specified or the product of the two function arguments specified. Argument numbering starts at one.
For instance,
void* my_calloc(size_t, size_t) __attribute__((alloc_size(1,2))) void* my_realloc(void*, size_t) __attribute__((alloc_size(2)))
declares that my_calloc
returns memory of the size given by
the product of parameter 1 and 2 and that my_realloc
returns memory
of the size given by parameter 2.
always_inline
artificial
assume_aligned
assume_aligned
attribute is used to tell the compiler that the
function return value points to memory, where the returned pointer minimum
alignment is given by the first argument.
If the attribute has two arguments, the second argument is misalignment offset.
For instance
void* my_alloc1(size_t) __attribute__((assume_aligned(16))) void* my_alloc2(size_t) __attribute__((assume_aligned(32, 8)))
declares that my_alloc1
returns 16-byte aligned pointer and
that my_alloc2
returns a pointer whose value modulo 32 is equal
to 8.
bnd_instrument
bnd_instrument
attribute on functions is used to inform the
compiler that the function should be instrumented when compiled
with the -fchkp-instrument-marked-only option.
bnd_legacy
bnd_legacy
attribute on functions is used to inform the
compiler that the function should not be instrumented when compiled
with the -fcheck-pointer-bounds option.
cold
cold
attribute on functions is used to inform the compiler that
the function is unlikely to be executed. The function is optimized for
size rather than speed and on many targets it is placed into a special
subsection of the text section so all cold functions appear close together,
improving code locality of non-cold parts of program. The paths leading
to calls of cold functions within code are marked as unlikely by the branch
prediction mechanism. It is thus useful to mark functions used to handle
unlikely conditions, such as perror
, as cold to improve optimization
of hot functions that do call marked functions in rare occasions.
When profile feedback is available, via -fprofile-use, cold functions
are automatically detected and this attribute is ignored.
const
const
attribute imposes greater restrictions on a function's
definition than the similar pure
attribute below because it prohibits
the function from reading global variables. Consequently, the presence of
the attribute on a function declaration allows GCC to emit more efficient
code for some calls to the function. Decorating the same function with
both the const
and the pure
attribute is diagnosed.
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
. Because a const
function cannot have any side
effects it does not make sense for such a function to return void
.
Declaring such a function is diagnosed.
constructor
destructor
constructor (
priority)
destructor (
priority)
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 ()
completes or exit ()
is
called. Functions with these attributes are useful for
initializing data that is used implicitly during the execution of
the program.
You may provide an optional integer priority to control the order in
which constructor and destructor functions are run. A constructor
with a smaller priority number runs before a constructor with a larger
priority number; the opposite relationship holds for destructors. So,
if you have a constructor that allocates a resource and a destructor
that deallocates the same resource, both functions typically have the
same priority. The priorities for constructor and destructor
functions are the same as those specified for namespace-scope C++
objects (see C++ Attributes). However, at present, the order in which
constructors for C++ objects with static storage duration and functions
decorated with attribute constructor
are invoked is unspecified.
In mixed declarations, attribute init_priority
can be used to
impose a specific ordering.
deprecated
deprecated (
msg)
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 optional msg argument, which must be a string, is printed in the warning if present.
The deprecated
attribute can also be used for variables and
types (see Variable Attributes, see Type Attributes.)
error ("
message")
warning ("
message")
error
or warning
attribute
is used on a function declaration and a call to such a function
is not eliminated through dead code elimination or other optimizations,
an error or warning (respectively) that includes message is diagnosed.
This is useful
for compile-time checking, especially together with __builtin_constant_p
and inline functions where checking the inline function arguments is not
possible through extern char [(condition) ? 1 : -1];
tricks.
While it is possible to leave the function undefined and thus invoke
a link failure (to define the function with
a message in .gnu.warning*
section),
when using these attributes the problem is diagnosed
earlier and with exact location of the call even in presence of inline
functions or when not emitting debugging information.
externally_visible
If -fwhole-program is used together with -flto and
gold is used as the linker plugin,
externally_visible
attributes are automatically added to functions
(not variable yet due to a current gold issue)
that are accessed outside of LTO objects according to resolution file
produced by gold.
For other linkers that cannot generate resolution file,
explicit externally_visible
attributes are still necessary.
flatten
format (
archetype,
string-index,
first-to-check)
format
attribute specifies that a function takes printf
,
scanf
, strftime
or strfmon
style arguments that
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
,
gnu_printf
, gnu_scanf
, gnu_strftime
or
strfmon
. (You can also use __printf__
,
__scanf__
, __strftime__
or __strfmon__
.) On
MinGW targets, ms_printf
, ms_scanf
, and
ms_strftime
are also present.
archetype values such as printf
refer to the formats accepted
by the system's C runtime library,
while values prefixed with ‘gnu_’ always refer
to the formats accepted by the GNU C Library. On Microsoft Windows
targets, values prefixed with ‘ms_’ refer to the formats accepted by the
msvcrt.dll library.
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.
Since non-static C++ methods have an implicit this
argument, the
arguments of such methods should be counted from two, not one, when
giving values for string-index and first-to-check.
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
that take format strings as arguments, so that GCC can check the
calls to these functions for errors. The compiler always (unless
-ffreestanding or -fno-builtin 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.
For Objective-C dialects, NSString
(or __NSString__
) is
recognized in the same context. Declarations including these format attributes
are parsed for correct syntax, however the result of checking of such format
strings is not yet defined, and is not carried out by this version of the
compiler.
The target may also provide additional types of format checks.
See Format Checks Specific to Particular Target Machines.
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 the my_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 one). Since non-static C++ methods have
an implicit this
argument, the arguments of such methods should
be counted from two.
The format_arg
attribute allows you to identify your own
functions that 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 or -fno-builtin
is used. See Options Controlling C Dialect.
For Objective-C dialects, the format-arg
attribute may refer to an
NSString
reference for compatibility with the format
attribute
above.
The target may also allow additional types in format-arg
attributes.
See Format Checks Specific to Particular Target Machines.
gnu_inline
inline
keyword. It directs GCC to treat the function
as if it were defined in gnu90 mode even when compiling in C99 or
gnu99 mode.
If the function is declared extern
, then this definition of the
function is used only for inlining. In no case is the function
compiled as a standalone function, not even if you take its address
explicitly. Such an address becomes an external reference, as if you
had only declared the function, and had not defined it. This has
almost the effect of a macro. The way to use this is to put a
function definition in a header file with this attribute, and put
another copy of the function, without extern
, in a library
file. The definition in the header file causes most calls to the
function to be inlined. If any uses of the function remain, they
refer to the single copy in the library. Note that the two
definitions of the functions need not be precisely the same, although
if they do not have the same effect your program may behave oddly.
In C, if the function is neither extern
nor static
, then
the function is compiled as a standalone function, as well as being
inlined where possible.
This is how GCC traditionally handled functions declared
inline
. Since ISO C99 specifies a different semantics for
inline
, this function attribute is provided as a transition
measure and as a useful feature in its own right. This attribute is
available in GCC 4.1.3 and later. It is available if either of the
preprocessor macros __GNUC_GNU_INLINE__
or
__GNUC_STDC_INLINE__
are defined. See An Inline Function is As Fast As a Macro.
In C++, this attribute does not depend on extern
in any way,
but it still requires the inline
keyword to enable its special
behavior.
hot
hot
attribute on a function is used to inform the compiler that
the function is a hot spot of the compiled program. The function is
optimized more aggressively and on many targets it is placed into a special
subsection of the text section so all hot functions appear close together,
improving locality.
When profile feedback is available, via -fprofile-use, hot functions
are automatically detected and this attribute is ignored.
ifunc ("
resolver")
ifunc
attribute is used to mark a function as an indirect
function using the STT_GNU_IFUNC symbol type extension to the ELF
standard. This allows the resolution of the symbol value to be
determined dynamically at load time, and an optimized version of the
routine to be selected for the particular processor or other system
characteristics determined then. To use this attribute, first define
the implementation functions available, and a resolver function that
returns a pointer to the selected implementation function. The
implementation functions' declarations must match the API of the
function being implemented. The resolver should be declared to
be a function taking no arguments and returning a pointer to
a function of the same type as the implementation. For example:
void *my_memcpy (void *dst, const void *src, size_t len) { ... return dst; } static void * (*resolve_memcpy (void))(void *, const void *, size_t) { return my_memcpy; // we will just always select this routine }
The exported header file declaring the function the user calls would contain:
extern void *memcpy (void *, const void *, size_t);
allowing the user to call memcpy
as a regular function, unaware of
the actual implementation. Finally, the indirect function needs to be
defined in the same translation unit as the resolver function:
void *memcpy (void *, const void *, size_t) __attribute__ ((ifunc ("resolve_memcpy")));
In C++, the ifunc
attribute takes a string that is the mangled name
of the resolver function. A C++ resolver for a non-static member function
of class C
should be declared to return a pointer to a non-member
function taking pointer to C
as the first argument, followed by
the same arguments as of the implementation function. G++ checks
the signatures of the two functions and issues
a -Wattribute-alias warning for mismatches. To suppress a warning
for the necessary cast from a pointer to the implementation member function
to the type of the corresponding non-member function use
the -Wno-pmf-conversions option. For example:
class S { private: int debug_impl (int); int optimized_impl (int); typedef int Func (S*, int); static Func* resolver (); public: int interface (int); }; int S::debug_impl (int) { /* ... */ } int S::optimized_impl (int) { /* ... */ } S::Func* S::resolver () { int (S::*pimpl) (int) = getenv ("DEBUG") ? &S::debug_impl : &S::optimized_impl; // Cast triggers -Wno-pmf-conversions. return reinterpret_cast<Func*>(pimpl); } int S::interface (int) __attribute__ ((ifunc ("_ZN1S8resolverEv")));
Indirect functions cannot be weak. Binutils version 2.20.1 or higher
and GNU C Library version 2.11.1 are required to use this feature.
interrupt
interrupt_handler
leaf
longjmp
into the unit. Leaf functions
might still call functions from other compilation units and thus they
are not necessarily leaf in the sense that they contain no function
calls at all.
The attribute is intended for library functions to improve dataflow
analysis. The compiler takes the hint that any data not escaping the
current compilation unit cannot be used or modified by the leaf
function. For example, the sin
function is a leaf function, but
qsort
is not.
Note that leaf functions might indirectly run a signal handler defined
in the current compilation unit that uses static variables. Similarly,
when lazy symbol resolution is in effect, leaf functions might invoke
indirect functions whose resolver function or implementation function is
defined in the current compilation unit and uses static variables. There
is no standard-compliant way to write such a signal handler, resolver
function, or implementation function, and the best that you can do is to
remove the leaf
attribute or mark all such static variables
volatile
. Lastly, for ELF-based systems that support symbol
interposition, care should be taken that functions defined in the
current compilation unit do not unexpectedly interpose other symbols
based on the defined standards mode and defined feature test macros;
otherwise an inadvertent callback would be added.
The attribute has no effect on functions defined within the current
compilation unit. This is to allow easy merging of multiple compilation
units into one, for example, by using the link-time optimization. For
this reason the attribute is not allowed on types to annotate indirect
calls.
malloc
malloc
-like, i.e.,
that the pointer P returned by the function cannot alias any
other pointer valid when the function returns, and moreover no
pointers to valid objects occur in any storage addressed by P.
Using this attribute can improve optimization. Functions like
malloc
and calloc
have this property because they return
a pointer to uninitialized or zeroed-out storage. However, functions
like realloc
do not have this property, as they can return a
pointer to storage containing pointers.
no_icf
no_instrument_function
no_profile_instrument_function
no_profile_instrument_function
attribute on functions is used
to inform the compiler that it should not process any profile feedback based
optimization code instrumentation.
no_reorder
no_reorder
against each other or top level assembler statements the executable.
The actual order in the program will depend on the linker command
line. Static variables marked like this are also not removed.
This has a similar effect
as the -fno-toplevel-reorder option, but only applies to the
marked symbols.
no_sanitize ("
sanitize_option")
no_sanitize
attribute on functions is used
to inform the compiler that it should not do sanitization of all options
mentioned in sanitize_option. A list of values acceptable by
-fsanitize option can be provided.
void __attribute__ ((no_sanitize ("alignment", "object-size"))) f () { /* Do something. */; } void __attribute__ ((no_sanitize ("alignment,object-size"))) g () { /* Do something. */; }
no_sanitize_address
no_address_safety_analysis
no_sanitize_address
attribute on functions is used
to inform the compiler that it should not instrument memory accesses
in the function when compiling with the -fsanitize=address option.
The no_address_safety_analysis
is a deprecated alias of the
no_sanitize_address
attribute, new code should use
no_sanitize_address
.
no_sanitize_thread
no_sanitize_thread
attribute on functions is used
to inform the compiler that it should not instrument memory accesses
in the function when compiling with the -fsanitize=thread option.
no_sanitize_undefined
no_sanitize_undefined
attribute on functions is used
to inform the compiler that it should not check for undefined behavior
in the function when compiling with the -fsanitize=undefined option.
no_split_stack
no_split_stack
attribute do not have that prologue, and thus
may run with only a small amount of stack space available.
no_stack_limit
noclone
noinline
asm ("");
(see Extended Asm) in the called function, to serve as a special
side effect.
noipa
noinline
, noclone
and
no_icf
attributes. However, this attribute is not equivalent
to a combination of other attributes, because its purpose is to suppress
existing and future optimizations employing interprocedural analysis,
including those that do not have an attribute suitable for disabling
them individually. This attribute is supported mainly for the purpose
of testing the compiler.
nonnull (
arg-index, ...)
nonnull
attribute specifies that some function parameters should
be non-null pointers. For instance, the declaration:
extern void * my_memcpy (void *dest, const void *src, size_t len) __attribute__((nonnull (1, 2)));
causes the compiler to check that, in calls to my_memcpy
,
arguments dest and src are non-null. If the compiler
determines that a null pointer is passed in an argument slot marked
as non-null, and the -Wnonnull option is enabled, a warning
is issued. The compiler may also choose to make optimizations based
on the knowledge that certain function arguments will never be null.
If no argument index list is given to the nonnull
attribute,
all pointer arguments are marked as non-null. To illustrate, the
following declaration is equivalent to the previous example:
extern void * my_memcpy (void *dest, const void *src, size_t len) __attribute__((nonnull));
noplt
noplt
attribute is the counterpart to option -fno-plt.
Calls to functions marked with this attribute in position-independent code
do not use the PLT.
/* Externally defined function foo. */ int foo () __attribute__ ((noplt)); int main (/* ... */) { /* ... */ foo (); /* ... */ }
The noplt
attribute on function foo
tells the compiler to assume that
the function foo
is externally defined and that the call to
foo
must avoid the PLT
in position-independent code.
In position-dependent code, a few targets also convert calls to
functions that are marked to not use the PLT to use the GOT instead.
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.
The noreturn
keyword does not affect the exceptional path when that
applies: a noreturn
-marked function may still return to the caller
by throwing an exception or calling longjmp
.
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
.
nothrow
nothrow
attribute is used to inform the compiler that a
function cannot throw an exception. For example, most functions in
the standard C library can be guaranteed not to throw an exception
with the notable exceptions of qsort
and bsearch
that
take function pointer arguments.
optimize
optimize
attribute is used to specify that a function is to
be compiled with different optimization options than specified on the
command line. Arguments can either be numbers or strings. Numbers
are assumed to be an optimization level. Strings that begin with
O
are assumed to be an optimization option, while other options
are assumed to be used with a -f
prefix. You can also use the
‘#pragma GCC optimize’ pragma to set the optimization options
that affect more than one function.
See Function Specific Option Pragmas, for details about the
‘#pragma GCC optimize’ pragma.
This attribute should be used for debugging purposes only. It is not
suitable in production code.
patchable_function_entry
The patchable_function_entry
function attribute can be used to
change the number of NOPs to any desired value. The two-value syntax
is the same as for the command-line switch
-fpatchable-function-entry=N,M, generating N NOPs, with
the function entry point before the Mth NOP instruction.
M defaults to 0 if omitted e.g. function entry point is before
the first NOP.
If patchable function entries are enabled globally using the command-line
option -fpatchable-function-entry=N,M, then you must disable
instrumentation on all functions that are part of the instrumentation
framework with the attribute patchable_function_entry (0)
to prevent recursion.
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 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 pure
attribute imposes similar but looser restrictions on
a function's defintion than the const
attribute: it allows the
function to read global variables. Decorating the same function with
both the pure
and the const
attribute is diagnosed.
Because a pure
function cannot have any side effects it does not
make sense for such a function to return void
. Declaring such
a function is diagnosed.
returns_nonnull
returns_nonnull
attribute specifies that the function
return value should be a non-null pointer. For instance, the declaration:
extern void * mymalloc (size_t len) __attribute__((returns_nonnull));
lets the compiler optimize callers based on the knowledge
that the return value will never be null.
returns_twice
returns_twice
attribute tells the compiler that a function may
return more than one time. The compiler ensures that all registers
are dead before calling such a function and emits a warning about
the variables that may be clobbered after the second return from the
function. Examples of such functions are setjmp
and vfork
.
The longjmp
-like counterpart of such function, if any, might need
to be marked with the noreturn
attribute.
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.
sentinel
NULL
. The attribute is only valid on variadic
functions. By default, the sentinel is located at position zero, the
last parameter of the function call. If an optional integer position
argument P is supplied to the attribute, the sentinel must be located at
position P counting backwards from the end of the argument list.
__attribute__ ((sentinel)) is equivalent to __attribute__ ((sentinel(0)))
The attribute is automatically set with a position of 0 for the built-in
functions execl
and execlp
. The built-in function
execle
has the attribute set with a position of 1.
A valid NULL
in this context is defined as zero with any pointer
type. If your system defines the NULL
macro with an integer type
then you need to add an explicit cast. GCC replaces stddef.h
with a copy that redefines NULL appropriately.
The warnings for missing or incorrect sentinels are enabled with
-Wformat.
simd
simd("
mask")
The optional argument mask may have the value
notinbranch
or inbranch
,
and instructs the compiler to generate non-masked or masked
clones correspondingly. By default, all clones are generated.
If the attribute is specified and #pragma omp declare simd
is
present on a declaration and the -fopenmp or -fopenmp-simd
switch is specified, then the attribute is ignored.
stack_protect
target (
options)
target
attribute
to specify that a function is to
be compiled with different target options than specified on the
command line. This can be used for instance to have functions
compiled with a different ISA (instruction set architecture) than the
default. You can also use the ‘#pragma GCC target’ pragma to set
more than one function to be compiled with specific target options.
See Function Specific Option Pragmas, for details about the
‘#pragma GCC target’ pragma.
For instance, on an x86, you could declare one function with the
target("sse4.1,arch=core2")
attribute and another with
target("sse4a,arch=amdfam10")
. This is equivalent to
compiling the first function with -msse4.1 and
-march=core2 options, and the second function with
-msse4a and -march=amdfam10 options. It is up to you
to make sure that a function is only invoked on a machine that
supports the particular ISA it is compiled for (for example by using
cpuid
on x86 to determine what feature bits and architecture
family are used).
int core2_func (void) __attribute__ ((__target__ ("arch=core2"))); int sse3_func (void) __attribute__ ((__target__ ("sse3")));
You can either use multiple strings separated by commas to specify multiple options, or separate the options with a comma (‘,’) within a single string.
The options supported are specific to each target; refer to x86 Function Attributes, PowerPC Function Attributes,
ARM Function Attributes, AArch64 Function Attributes,
Nios II Function Attributes, and S/390 Function Attributes
for details.
target_clones (
options)
target_clones
attribute is used to specify that a function
be cloned into multiple versions compiled with different target options
than specified on the command line. The supported options and restrictions
are the same as for target
attribute.
For instance, on an x86, you could compile a function with
target_clones("sse4.1,avx")
. GCC creates two function clones,
one compiled with -msse4.1 and another with -mavx.
On a PowerPC, you can compile a function with
target_clones("cpu=power9,default")
. GCC will create two
function clones, one compiled with -mcpu=power9 and another
with the default options. GCC must be configured to use GLIBC 2.23 or
newer in order to use the target_clones
attribute.
It also creates a resolver function (see
the ifunc
attribute above) that dynamically selects a clone
suitable for current architecture. The resolver is created only if there
is a usage of a function with target_clones
attribute.
unused
used
When applied to a member function of a C++ class template, the
attribute also means that the function is instantiated if the
class itself is instantiated.
visibility ("
visibility_type")
There are four supported visibility_type values: default, hidden, protected or internal visibility.
void __attribute__ ((visibility ("protected")))
f () { /* Do something. */; }
int i __attribute__ ((visibility ("hidden")));
The possible values of visibility_type correspond to the visibility settings in the ELF gABI.
default
On ELF, default visibility means that the declaration is visible to other modules and, in shared libraries, means that the declared entity may be overridden.
On Darwin, default visibility means that the declaration is visible to other modules.
Default visibility corresponds to “external linkage” in the language.
hidden
internal
protected
All visibilities are supported on many, but not all, ELF targets (supported when the assembler supports the ‘.visibility’ pseudo-op). Default visibility is supported everywhere. Hidden visibility is supported on Darwin targets.
The visibility attribute should be applied only to declarations that would otherwise have external linkage. The attribute should be applied consistently, so that the same entity should not be declared with different settings of the attribute.
In C++, the visibility attribute applies to types as well as functions and objects, because in C++ types have linkage. A class must not have greater visibility than its non-static data member types and bases, and class members default to the visibility of their class. Also, a declaration without explicit visibility is limited to the visibility of its type.
In C++, you can mark member functions and static member variables of a class with the visibility attribute. This is useful if you know a particular method or static member variable should only be used from one shared object; then you can mark it hidden while the rest of the class has default visibility. Care must be taken to avoid breaking the One Definition Rule; for example, it is usually not useful to mark an inline method as hidden without marking the whole class as hidden.
A C++ namespace declaration can also have the visibility attribute.
namespace nspace1 __attribute__ ((visibility ("protected")))
{ /* Do something. */; }
This attribute applies only to the particular namespace body, not to other definitions of the same namespace; it is equivalent to using ‘#pragma GCC visibility’ before and after the namespace definition (see Visibility Pragmas).
In C++, if a template argument has limited visibility, this restriction is implicitly propagated to the template instantiation. Otherwise, template instantiations and specializations default to the visibility of their template.
If both the template and enclosing class have explicit visibility, the
visibility from the template is used.
warn_unused_result
warn_unused_result
attribute causes a warning to be emitted
if a caller of the function with this attribute does not use its
return value. This is useful for functions where not checking
the result is either a security problem or always a bug, such as
realloc
.
int fn () __attribute__ ((warn_unused_result)); int foo () { if (fn () < 0) return -1; fn (); return 0; }
results in warning on line 5.
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 that 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.
weakref
weakref ("
target")
weakref
attribute marks a declaration as a weak reference.
Without arguments, it should be accompanied by an alias
attribute
naming the target symbol. Optionally, the target may be given as
an argument to weakref
itself. In either case, weakref
implicitly marks the declaration as weak
. Without a
target, given as an argument to weakref
or to alias
,
weakref
is equivalent to weak
.
static int x() __attribute__ ((weakref ("y"))); /* is equivalent to... */ static int x() __attribute__ ((weak, weakref, alias ("y"))); /* and to... */ static int x() __attribute__ ((weakref)); static int x() __attribute__ ((alias ("y")));
A weak reference is an alias that does not by itself require a
definition to be given for the target symbol. If the target symbol is
only referenced through weak references, then it becomes a weak
undefined symbol. If it is directly referenced, however, then such
strong references prevail, and a definition is required for the
symbol, not necessarily in the same translation unit.
The effect is equivalent to moving all references to the alias to a separate translation unit, renaming the alias to the aliased symbol, declaring it as weak, compiling the two separate translation units and performing a reloadable link on them.
At present, a declaration to which weakref
is attached can
only be static
.