6.4.1 Common Attributes

The following GNU-specific attributes are supported on most targets in both C and C++. When using the standard syntax, you must prefix their names with ‘gnu::’, such as gnu::section.

See C++-Specific Variable, Function, and Type Attributes, for additional GNU attributes that are specific to C++.

With the -fopenmp option, GCC additionally recognizes OpenMP directives, with names prefixed with ‘omp::’, using the standard ‘[[]]’ syntax. See OpenMP.

access (access-mode, ref-index)
access (access-mode, ref-index, size-index)

This attribute applies to functions.

The access attribute enables the detection of invalid or unsafe accesses by functions or their callers, as well as write-only accesses to objects that are never read from. Such accesses may be diagnosed by warnings such as -Wstringop-overflow, -Wuninitialized, -Wunused, and others.

The access attribute specifies that a pointer or reference argument to the function is accessed according to access-mode, which must be one of read_only, read_write, write_only, or none. The semantics of these modes are described below.

The argument the attribute applies to is identifed by ref-index, which is an integer constant representing its position in the argument list. Argument numbering starts from 1. You can specify multiple access attributes to describe the access modes of different arguments, but multiple access attributes applying to the same argument are not permitted.

The optional size-index denotes the position of a function argument of integer type that specifies the maximum size of the access. The size is the number of elements of the type referenced by ref-index, or the number of bytes when the pointer type is void*. When no size-index argument is specified, the pointer argument must be either null or point to a space that is suitably aligned and large enough for at least one object of the referenced type (this implies that a past-the-end pointer is not a valid argument). The actual size of the access may be less but it must not be more.

The read_only access mode specifies that the pointer to which it applies is used to read the referenced object but not write to it. Unless the argument specifying the size of the access denoted by size-index is zero, the referenced object must be initialized. The mode implies a stronger guarantee than the const qualifier which, when cast away from a pointer, does not prevent the pointed-to object from being modified. Examples of the use of the read_only access mode is the argument to the puts function, or the second argument to the memcpy function.

[[gnu::access (read_only, 1)]]
int puts (const char*);

[[gnu::access (read_only, 2, 3)]]
void* memcpy (void*, const void*, size_t);

The read_write access mode applies to arguments of pointer types without the const qualifier. It specifies that the pointer to which it applies is used to both read and write the referenced object. Unless the argument specifying the size of the access denoted by size-index is zero, the object referenced by the pointer must be initialized. An example of the use of the read_write access mode is the first argument to the strcat function.

[[gnu::access (read_write, 1), gnu::access (read_only, 2)]]
char* strcat (char*, const char*);

The write_only access mode applies to arguments of pointer types without the const qualifier. It specifies that the pointer to which it applies is used to write to the referenced object but not read from it. The object referenced by the pointer need not be initialized. An example of the use of the write_only access mode is the first argument to the strcpy function, or the first two arguments to the fgets function.

__attribute__ ((access (write_only, 1), access (read_only, 2)))
char* strcpy (char*, const char*);

__attribute__ ((access (write_only, 1, 2), access (read_write, 3)))
int fgets (char*, int, FILE*);

The access mode none specifies that the pointer argument to which it applies is not used to access the referenced object at all. Unless the pointer is null, the pointed-to object must exist and have at least the size as denoted by the size-index argument. When the optional size-index argument is omitted for an argument of void* type, the actual pointer argument is ignored. The referenced object need not be initialized. The mode is intended to be used as a means to help validate the expected object size, for example in functions that call __builtin_object_size. See Object Size Checking.

Note that the access attribute merely specifies how an object referenced by the pointer argument can be accessed; it does not imply that an access will happen. Also, the access attribute does not imply the attribute nonnull nor the attribute nonnull_if_nonzero; it may be appropriate to add both attributes at the declaration of a function that unconditionally manipulates a buffer via a pointer argument. See the nonnull or nonnull_if_nonzero function attributes, documented later in this section, for more information and caveats.

alias ("target")

This attribute applies to variables and functions.

The alias attribute causes the declaration to be emitted as an alias for another symbol known as an alias target.

For instance, the following

int var_target;
extern int var_alias [[gnu::alias ("var_target")]];

defines var_alias to be an alias for the var_target variable, and

void __f () { /* Do something. */; }
void f () __attribute__ ((weak, alias ("__f")));

defines ‘f’ to be a weak alias for ‘__f’.

Except for top-level qualifiers the alias target must have the same type as the alias. For variables, it must also have the same size and alignment.

The alias target must be defined in the same translation unit as the alias. In C++, the mangled name for the target must be used.

Note that in the absence of the attribute GCC assumes that distinct declarations with external linkage denote distinct objects. Using both the alias and the alias target to access the same object is undefined in a translation unit without a declaration of the alias with the attribute.

This attribute requires assembler and object file support, and may not be available on all targets.

aligned
aligned (alignment)

This attribute applies to functions, variables, typedefs, structs, and structure fields.

The aligned attribute specifies a minimum alignment for the entity it applies to, measured in bytes. When specified, alignment must be an integer constant power of 2.

For example, the declaration:

int x [[gnu::aligned (16)]] = 0;

causes the compiler to allocate the global variable x on a 16-byte boundary.

These declarations:

struct __attribute__ ((aligned (8))) S { short f[3]; };
typedef int more_aligned_int __attribute__ ((aligned (8)));

force the compiler to ensure (as far as it can) that each variable whose type is struct S or more_aligned_int is allocated and aligned at least on a 8-byte boundary.

When applied to a function, specifying no alignment argument implies the ideal alignment for the target. The __alignof__ operator can be used to determine what that is (see Determining the Alignment of Functions, Types or Variables). The attribute has no effect when a definition for the function is not provided in the same translation unit.

The attribute cannot be used to decrease the alignment of a function previously declared with a more restrictive alignment; only to increase it. Attempts to do otherwise are diagnosed. Some targets specify a minimum default alignment for functions that is greater than 1. On such targets, specifying a less restrictive alignment is silently ignored. Using the attribute overrides the effect of the -falign-functions (see Options That Control Optimization) option for this function.

For variables, types, and structure fields, increasing the alignment from the default can allow object copying to use larger chunks and make pointer arithmetic and array addressing more efficient. For example, some architectures can load and store 64-bit values only if they are aligned on 8-byte boundaries in memory. Explicitly aligning a structure type that contains two 32-bit fields on an 8-byte boundary allows it to be copied with a single pair of 64-bit load and store instructures instead of 2 pairs of 32-bit operations.

Omitting the alignment from the attribute implies the default maximum alignment for the target architecture you are compiling for. This is sufficient for all scalar types, but may not be enough for all vector types on a target that supports vector operations. The default alignment is fixed for a particular target ABI.

GCC also provides a target specific macro __BIGGEST_ALIGNMENT__, which is the largest alignment ever used for any data type on the target machine you are compiling for. For example, you could write:

short array[3] [[gnu::aligned (__BIGGEST_ALIGNMENT__)]];

This makes the compiler set the alignment for array to __BIGGEST_ALIGNMENT__. Note that the value of __BIGGEST_ALIGNMENT__ may change depending on command-line options.

When used on a struct, or struct member, the aligned attribute can only increase the alignment; in order to decrease it, the packed attribute must be specified as well. When used as part of a typedef, the aligned attribute can both increase and decrease alignment, and specifying the packed attribute generates a warning.

The alignment of any given struct or union type is required by the ISO C standard to be at least a perfect multiple of the lowest common multiple of the alignments of all of the members of the struct or union in question. This means that you can effectively adjust the alignment of a struct or union type by attaching an aligned attribute to any one of the members of such a type, but the notation illustrated in the example above is a more obvious, intuitive, and readable way to request the compiler to adjust the alignment of an entire struct or union type.

Note that the effectiveness of aligned attributes may be limited by inherent limitations in the system linker and/or object file format. On some systems, the linker is only able to arrange for functions or data 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.

Stack variables are not affected by linker restrictions; GCC can properly align them on any target.

alloc_align (position)

The alloc_align attribute may be applied to a function that returns a pointer and takes at least one argument of an integer or enumerated type.

It indicates that the returned pointer is aligned on a boundary given by the function argument at position. Meaningful alignments are powers of 2 greater than one. GCC uses this information to improve pointer alignment analysis.

The function parameter denoting the allocated alignment is specified by one constant 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 (position)
alloc_size (position-1, position-2)

The alloc_size attribute may be applied to a function that returns a pointer and takes at least one argument of an integer or enumerated type, or to the declaration of the type of such a function, or a type or variable with a type of pointer to such a function.

It indicates that the returned pointer points to memory whose size is given by the function argument at position-1, or by the product of the arguments at position-1 and position-2. Meaningful sizes are positive values less than PTRDIFF_MAX. GCC uses this information to improve the results 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 ordinary functions, and at two for C++ non-static member functions.

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.

Similarly, the following declarations

typedef __attribute__ ((alloc_size (1, 2))) void*
  (*calloc_ptr) (size_t, size_t);
typedef __attribute__ ((alloc_size (1))) void*
  (*malloc_ptr) (size_t);

specify that calloc_ptr is a pointer to a function that, like the standard C function calloc, returns an object whose size is given by the product of arguments 1 and 2, and similarly, that malloc_ptr, like the standard C function malloc, is a pointer to a function that returns an object whose size is given by argument 1 to the function.

always_inline

The always_inline attribute applies to functions.

Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function independent of any restrictions that otherwise apply to inlining. Failure to inline such a function is diagnosed as an error. Note that if such a function is called indirectly the compiler may or may not inline it depending on optimization level and a failure to inline an indirect call may or may not be diagnosed.

If you need to use the inlined function in multiple translation units, you should put the always_inline attribute on a function definition in a header file that is included in all translation units where the function is used. Link-time optimization can inline functions across translation units, but only if an optimization level that normally enables inlining is additionally specified.

artificial

This attribute applies to functions.

The artificial attribute is useful for small inline wrappers that, if possible, should appear during debugging as a unit. Depending on the debug info format it either means marking the function as artificial or using the caller location for all instructions within the inlined body.

assume

This is a statement attribute that can appear only as an attribute declaration.

The assume attribute with a null statement serves as portable assumption. It should have a single argument, a conditional expression, which is not evaluated. If the argument would evaluate to true at the point where it appears, it has no effect, otherwise there is undefined behavior. This is a GNU variant of the ISO C++23 standard assume attribute, but it can be used in any version of both C and C++.

int
foo (int x, int y)
{
  [[gnu::assume(x == 42)]];
  [[gnu::assume(++y == 43)]];
  return x + y;
}

y is not actually incremented and the compiler can but does not have to optimize it to just return 42 + 42;.

assume_aligned (alignment)
assume_aligned (alignment, offset)

The assume_aligned attribute may be applied to a function that returns a pointer.

It indicates that the returned pointer is aligned on a boundary given by alignment. If the attribute has two arguments, the second argument is misalignment offset. Meaningful values of alignment are powers of 2 greater than one. Meaningful values of offset are greater than zero and less than alignment.

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 pointers and that my_alloc2 returns a pointer whose value modulo 32 is equal to 8.

btf_decl_tag

This attribute can be applied to functions, variables, struct or union member declarations, and function parameter declarations.

The btf_decl_tag attribute associates the entity it applies to with an arbitrary string. These strings are not interpreted by the compiler in any way, and have no effect on code generation. Instead, these user-provided strings are recorded in DWARF (via DW_AT_GNU_annotation and DW_TAG_GNU_annotation extensions) and BTF information (via BTF_KIND_DECL_TAG records), and associated to the attributed declaration. If neither DWARF nor BTF information is generated, the attribute has no effect.

The argument is treated as a null-terminated sequence of zero or more non-null bytes. Wide character strings are not supported.

The attribute may be supplied multiple times for a single declaration, in which case each distinct argument string will be recorded in a separate DIE or BTF record, each associated to the declaration. For a single declaration with multiple btf_decl_tag attributes, the order of the DW_TAG_GNU_annotation DIEs produced is not guaranteed to maintain the order of attributes in the source code.

For example:

int *foo [[gnu::btf_decl_tag ("__percpu")]];

when compiled with -gbtf results in an additional BTF_KIND_DECL_TAG BTF record to be emitted in the BTF info, associating the string ‘__percpu’ with the BTF_KIND_VAR record for the variable foo.

btf_type_tag (argument)

This attribute applies to types.

The btf_type_tag attribute may be used to associate (to “tag”) particular types with arbitrary string annotations. These annotations are recorded in debugging info by supported debug formats, currently DWARF (via DW_AT_GNU_annotation and DW_TAG_GNU_annotation extensions) and BTF (via BTF_KIND_TYPE_TAG records). These annotation strings are not interpreted by the compiler in any way, and have no effect on code generation. If neither DWARF nor BTF information is generated, the attribute has no effect.

The argument is treated as a null-terminated sequence of zero or more non-null bytes. Wide character strings are not supported.

The attribute may be supplied multiple times for a single type, in which case each distinct argument string will be recorded in a separate DIE or BTF record, each associated to the type. For a single type with multiple btf_type_tag attributes, the order of the DW_TAG_GNU_annotation DIEs produced is not guaranteed to maintain the order of attributes in the source code.

For example the following code:

int * [[gnu::btf_type_tag ("__user")]] foo;

when compiled with -gbtf results in an additional BTF_KIND_TYPE_TAG BTF record to be emitted in the BTF info, associating the string ‘__user’ with the normal BTF_KIND_PTR record for the pointer-to-integer type used in the declaration.

Note that the BTF format currently only has a representation for type tags associated with pointer types. Type tags on non-pointer types may be silently skipped when generating BTF.

cleanup (cleanup_function)

This attribute applies to variables.

The cleanup attribute runs a function when the variable goes out of scope. This attribute can only be applied to auto function scope variables; it may not be applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.

When multiple variables in the same scope have cleanup attributes, at exit from the scope their associated cleanup functions are run in reverse order of definition (last defined, first cleanup).

If -fexceptions is enabled, then cleanup_function is run during the stack unwinding that happens during the processing of the exception. Note that the cleanup attribute does not allow the exception to be caught, only to perform an action. It is undefined what happens if cleanup_function does not return normally.

cold
hot

These attributes can apply to functions or labels. In C++, they can also apply to classes, structs, or unions.

The cold attribute on a function informs 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.

The hot attribute on a function informs 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.

In C++, the cold or hot attribute on a type has the effect of treating every member function of the type, including implicit special member functions, as having that attribute. If a member function is marked with the opposite hot or cold attribute, that takes precedence over the attribute specified on the class.

When profile feedback is available, via -fprofile-use, hot and cold functions are automatically detected and this attribute is ignored.

When used as a statement attribute associated with a label, the cold attribute informs the compiler that the path following the label is unlikely to be executed, and hot informs the compiler that the path following the label is more likely than paths that are not so annotated. This attribute is used in cases where __builtin_expect cannot be used, for instance with computed goto or asm goto.

common
nocommon

This attribute applies to variables.

The common attribute requests GCC to place a variable in “common” storage. The nocommon attribute requests the opposite—to allocate space for it directly.

These attributes override the default chosen by the -fno-common and -fcommon flags respectively.

const

This attribute applies to functions.

Calls to functions whose return value is not affected by changes to the observable state of the program and that have no observable effects on such state other than to return a value may lend themselves to optimizations such as common subexpression elimination. Declaring such functions with the const attribute allows GCC to avoid emitting some calls in repeated invocations of the function with the same argument values.

For example,

[[gnu::const]] int square (int);

tells GCC that subsequent calls to function square with the same argument value can be replaced by the result of the first call regardless of the statements in between.

The const attribute prohibits a function from reading objects that affect its return value between successive invocations. However, functions declared with the attribute can safely read objects that do not change their return value, such as non-volatile constants.

The const attribute imposes greater restrictions on a function’s definition than the similar pure attribute. Declaring the same function with both the const and the pure attribute is diagnosed. Because a const function cannot have any observable side effects it does not make sense for it to return void. Declaring such a function is diagnosed.

Note that a function that has pointer arguments and examines the data pointed to must not be declared const if the pointed-to data might change between successive invocations of the function. In general, since a function cannot distinguish data that might change from data that cannot, const functions should never take pointer or, in C++, reference arguments. Likewise, a function that calls a non-const function usually must not be const itself.

constructor
destructor
constructor (priority)
destructor (priority)

These attributes apply to functions.

The 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.

On most targets the attributes also accept an integer argument to specify a priority to control the order in which constructor and destructor functions are run. The priority argument is a constant integral expression bounded between 101 and 65535 inclusive; priorities 0-100 are reserved for use by the compiler and its runtime libraries. 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. Note without an argument, the priority argument is equivalent to 65535.

The order in which constructors for C++ objects with static storage duration are invoked relative to functions decorated with attribute constructor is normally unspecified. You can use attribute init_priority (see C++-Specific Variable, Function, and Type Attributes) on the declarations of namespace-scope C++ objects to impose a specific ordering; the priority for the init_priority attribute has the same effect as the priority for the constructor attribute.

Using the argument form of the constructor and destructor attributes on targets where the feature is not supported is rejected with an error. Only a few targets (typically those not using ELF object format, or the GNU linker) reject this usage.

When multiple attributes of this type is supplied, the last one is what sets the priority.

copy
copy (name)

The copy attribute can appear on function, variable, and type declarations.

It applies the set of attributes with which name has been declared to the declaration of the function, variable, or type to which the attribute is applied. The attribute is designed for libraries that define aliases or function resolvers that are expected to specify the same set of attributes as their targets. The copy attribute can be used with functions, variables, or types. However, the kind of symbol to which the attribute is applied (either function or variable) must match the kind of symbol to which the argument refers. The copy attribute copies only syntactic and semantic attributes but not attributes that affect a symbol’s linkage or visibility such as alias, visibility, or weak. The deprecated and target_clones attribute are also not copied.

For example, the StrongAlias macro below makes use of the alias and copy attributes to define an alias named alloc for function allocate declared with attributes alloc_size, malloc, and nothrow. Thanks to the __typeof__ operator the alias has the same type as the target function. As a result of the copy attribute the alias also shares the same attributes as the target.

#define StrongAlias(TargetFunc, AliasDecl)  \
  extern __typeof__ (TargetFunc) AliasDecl  \
    __attribute__ ((alias (#TargetFunc), copy (TargetFunc)));

extern __attribute__ ((alloc_size (1), malloc, nothrow))
  void* allocate (size_t);
StrongAlias (allocate, alloc);

As another example, suppose struct A below is defined in some third-party library header to have the alignment requirement N and to force a warning whenever a variable of the type is not so aligned due to attribute packed. Specifying the copy attribute on the definition on the unrelated struct B has the effect of copying all relevant attributes from the type referenced by the pointer expression to struct B.

struct __attribute__ ((aligned (N), warn_if_not_aligned (N)))
A { /* ... */ };
struct __attribute__ ((copy ( (struct A *)0)) B { /* ... */ };
counted_by (count)

The counted_by attribute may be attached to a C99 flexible array member or a pointer field of a structure.

It indicates that the number of the elements of the array that is held by the flexible array member field, or is pointed to by the pointer field, is given by the field named by the identifer count in the same structure as the flexible array member or the pointer field.

This attribute is available only in C for now. In C++ this attribute is ignored.

GCC may use this information to improve detection of object size information for such structures and provide better results in compile-time diagnostics and runtime features like the array bound sanitizer and the __builtin_dynamic_object_size.

For instance, the following code:

struct P {
  size_t count;
  char other;
  [[gnu::counted_by (count)]] char array[];
} *p;

specifies that the array is a flexible array member whose number of elements is given by the field count in the same structure.

struct PP {
  size_t count2;
  char other1;
  [[gnu::counted_by (count2)]] char *array2;
  int other2;
} *pp;

specifies that the array2 is an array that is pointed by the pointer field, and its number of elements is given by the field count2 in the same structure.

The field that represents the number of the elements should have an integer type. Otherwise, the compiler reports an error and ignores the attribute.

When the field that represents the number of the elements is assigned a negative integer value, the compiler treats the value as zero.

The counted_by attribute is not allowed for a pointer to function, or a pointer to a structure or union that includes a flexible array member. However, it is allowed for a pointer to non-void incomplete structure or union types, as long as the type could be completed before the first reference to the pointer.

The attribute is allowed for a pointer to void. However, warnings will be issued for such cases when -Wpointer-arith is specified. When this attribute is applied on a pointer to void, the size of each element of this pointer array is treated as 1.

An explicit counted_by annotation defines a relationship between two objects, p->array and p->count, and there are the following requirements on the relationship between this pair:

  • p->count must be initialized before the first reference to p->array;
  • p->array has at least p->count number of elements available all the time. This relationship must hold even after any of these related objects are updated during the program.

In addition to the above requirements, there is one more requirement between this pair if and only if p->array is an array that is pointed by the pointer field:

p->array and p->count can only be changed by changing the whole structure at the same time.

It’s the programmer’s responsibility to make sure the above requirements to be kept all the time. Otherwise the compiler reports warnings and the results of the array bound sanitizer and the __builtin_dynamic_object_size built-in are undefined.

One important feature of the attribute is that a reference to the flexible array member field uses the latest value assigned to the field that represents the number of the elements before that reference. For example,

  p->count = val1;
  p->array[20] = 0;  // ref1 to p->array
  p->count = val2;
  p->array[30] = 0;  // ref2 to p->array

In the above, ref1 uses val1 as the number of the elements in p->array, and ref2 uses val2 as the number of elements in p->array.

Note, however, the above feature is not valid for the pointer field.

deprecated
deprecated (msg)

This attribute can appear on function, variable, type, or enumerator declarations.

The deprecated attribute results in a warning if the entity it applies to 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 entity, to enable users to easily find further information about why it 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.

When applied to a type, warnings only occur for uses and also only if the type is being applied to an identifier that itself is not being declared as deprecated.

typedef int T1 __attribute__ ((deprecated));
T1 x;
typedef T1 T2;
T2 y;
typedef T1 T3 __attribute__ ((deprecated));
T3 z __attribute__ ((deprecated));

results in a warning on line 2 and 3 but not lines 4, 5, or 6. No warning is issued for line 4 because T2 is not explicitly deprecated. Line 5 has no warning because T3 is explicitly deprecated. Similarly for line 6.

This example uses the deprecated enumerator attribute to indicate the oldval enumerator is deprecated:

enum E {
  oldval __attribute__((deprecated)),
  newval
};

int
fn (void)
{
  return oldval;
}

The optional msg argument, which must be a string, is printed in the warning if present. The msg string is affected by the setting of the -fmessage-length option. Control characters in the msg string are replaced with escape sequences, and if the -fmessage-length option is set to 0 (its default value) then any newline characters are ignored.

designated_init

This attribute may only be applied to structure types.

It indicates that any initialization of an object of this type must use designated initializers rather than positional initializers. The intent of this attribute is to allow the programmer to indicate that a structure’s layout may change, and that therefore relying on positional initialization will result in future breakage.

GCC emits warnings based on this attribute by default; use -Wno-designated-init to suppress them.

error ("message")
warning ("message")

This attribute applies to functions.

If the 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.

expected_throw

This attribute applies to functions.

It tells the compiler the function is more likely to raise or propagate an exception than to return, loop forever, or terminate the program.

This hint is mostly ignored by the compiler. The only effect is when it’s applied to noreturn functions and ‘-fharden-control-flow-redundancy’ is enabled, and ‘-fhardcfr-check-noreturn-calls=not-always’ is not overridden.

externally_visible

This attribute applies to global variables and functions.

It nullifies the effect of the -fwhole-program command-line option, so the object remains visible outside the current compilation unit.

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 variables 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.

fallthrough

This statement attribute can appear only as an attribute declaration.

The fallthrough attribute serves as a fallthrough statement. It hints to the compiler that a statement that falls through to another case label, or user-defined label in a switch statement is intentional and thus the -Wimplicit-fallthrough warning must not trigger. The fallthrough attribute may appear at most once in each attribute list, and may not be mixed with other attributes. It can only be used in a switch statement (the compiler issues an error otherwise), after a preceding statement and before a logically succeeding case label, or user-defined label.

This example uses the fallthrough statement attribute to indicate that the -Wimplicit-fallthrough warning should not be emitted:

switch (cond)
  {
  case 1:
    bar (1);
    __attribute__((fallthrough));
  case 2:
    ...
  }
fd_arg (N)
fd_arg_read (N)
fd_arg_write (N)

These attributes may be applied to functions that take an open file descriptor at referenced argument N.

The fd_arg attribute indicates that the passed file descriptor must not have been closed. Therefore, when the analyzer is enabled with -fanalyzer, the analyzer may emit a -Wanalyzer-fd-use-after-close diagnostic if it detects a code path in which a function with this attribute is called with a closed file descriptor.

The attribute also indicates that the file descriptor must have been checked for validity before usage. Therefore, analyzer may emit a -Wanalyzer-fd-use-without-check diagnostic if it detects a code path in which a function with this attribute is called with a file descriptor that has not been checked for validity.

The fd_arg_read attribute is identical to fd_arg, but with the additional requirement that the function might read from the file descriptor, and thus, the file descriptor must not have been opened as write-only.

The analyzer may emit a -Wanalyzer-access-mode-mismatch diagnostic if it detects a code path in which a function with this attribute is called on a file descriptor opened with O_WRONLY.

Similarly, the fd_arg_write attribute is identical to fd_arg except that the analyzer may emit a -Wanalyzer-access-mode-mismatch diagnostic if it detects a code path in which a function with this attribute is called on a file descriptor opened with O_RDONLY.

flag_enum

This attribute may be applied to an enumerated type.

It indicates that its enumerators are used in bitwise operations, so e.g. -Wswitch should not warn about a case that corresponds to a bitwise combination of enumerators.

flatten

This attribute applies to functions.

Generally, inlining into a function is limited. For a function marked with this attribute, every call inside this function is inlined including the calls such inlining introduces to the function (but not recursive calls to the function itself), if possible. Functions declared with attribute noinline and similar are not inlined. Whether the function itself is considered for inlining depends on its size and the current inlining parameters.

format (archetype, string-index, first-to-check)

The format attribute applies to functions.

It specifies that the function takes printf, scanf, strftime or strfmon style arguments that should be type-checked against a format string. For example, the declaration:

[[gnu::format (printf, 2, 3)]]
extern int
my_printf (void *my_object, const char *my_format, ...);

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. Valid archetypes include printf, scanf, strftime, gnu_printf, gnu_scanf, gnu_strftime or strfmon. (You can also use __printf__, __scanf__, __strftime__ or __strfmon__.) 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 MinGW and Microsoft Windows targets, ms_printf, ms_scanf, and ms_strftime are also present. Values prefixed with ‘ms_’ refer to the formats accepted by the msvcrt.dll library.

Solaris targets also support the cmn_err (or __cmn_err__) archetype. cmn_err accepts a subset of the standard printf conversions, and the two-argument %b conversion for displaying bit-fields. See the Solaris man page for cmn_err for more information.

Darwin targets also support the CFString (or __CFString__) archetype in the format attribute. Declarations with this archetype are parsed for correct syntax and argument types. However, parsing of the format string itself and validating arguments against it in calls to such functions is currently not performed.

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 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.

format_arg (string-index)

The format_arg attribute applies to functions.

It specifies that the function takes one or more format strings 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). Multiple format_arg attributes may be applied to the same function, each designating a distinct parameter as a format 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.

In calls to a function declared with more than one format_arg attribute, each with a distinct argument value, the corresponding actual function arguments are checked against all format strings designated by the attributes. This capability is designed to support the GNU ngettext family of functions.

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.

Similarly, on Darwin targets CFStringRefs (defined by the CoreFoundation headers) may also be used as format arguments. Note that the relevant headers are only likely to be available on Darwin (OSX) installations. On such installations, the XCode and system documentation provide descriptions of CFString, CFStringRefs and associated functions.

gnu_inline

This attribute applies to functions.

It should be used with a function that is also declared with the 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.

hardbool
hardbool (false_value)
hardbool (false_value, true_value)

This attribute can be applied to integral types in C.

The hardbool attribute introduces hardened boolean types. It turns the integral type into a boolean-like type with the same size and precision, that uses the specified values as representations for false and true. Underneath, it is actually an enumerated type, but its observable behavior is like that of _Bool, except for the strict internal representations, verified by runtime checks.

If true_value is omitted, the bitwise negation of false_value is used. If false_value is omitted, zero is used. The named representation values must be different when converted to the original integral type. Narrower bitfields are rejected if the representations become indistinguishable.

Values of such types automatically decay to _Bool, at which point, the selected representation values are mapped to the corresponding _Bool values. When the represented value is not determined, at compile time, to be either false_value or true_value, runtime verification calls __builtin_trap if it is neither. This is what makes them hardened boolean types.

When converting scalar types to such hardened boolean types, implicitly or explicitly, behavior corresponds to a conversion to _Bool, followed by a mapping from false and true to false_value and true_value, respectively.

typedef char __attribute__ ((__hardbool__ (0x5a))) hbool;
hbool first = 0;       /* False, stored as (char)0x5a.  */
hbool second = !first; /* True, stored as ~(char)0x5a.  */

static hbool zeroinit; /* False, stored as (char)0x5a.  */
auto hbool uninit;     /* Undefined, may trap.  */

When zero-initializing a variable or field of hardened boolean type (presumably held in static storage) the implied zero initializer gets converted to _Bool, and then to the hardened boolean type, so that the initial value is the hardened representation for false. Using that value is well defined. This is not the case when variables and fields of such types are uninitialized (presumably held in automatic or dynamic storage): their values are indeterminate, and using them invokes undefined behavior. Using them may trap or not, depending on the bits held in the storage (re)used for the variable, if any, and on optimizations the compiler may perform on the grounds that using uninitialized values invokes undefined behavior.

Users of -ftrivial-auto-var-init should be aware that the bit patterns used as initializers are not converted to hardbool types, so using a hardbool variable that is implicitly initialized by the -ftrivial-auto-var-init may trap if the representations values chosen for false and true do not match the initializer.

Since this is a language extension only available in C, interoperation with other languages may pose difficulties. It should interoperate with Ada Booleans defined with the same size and equivalent representation clauses, and with enumerations or other languages’ integral types that correspond to C’s chosen integral type.

ifunc ("resolver")

This attribute applies to functions.

The 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

These attributes apply to functions.

Many GCC back ends support attributes to indicate that a function is an interrupt handler, which tells the compiler to generate function entry and exit sequences that differ from those from regular functions. The exact syntax and behavior are target-specific; refer to the following subsections for details.

leaf

This attribute applies to functions.

Calls to external functions with this attribute must return to the current compilation unit only by return or by exception handling. In particular, a leaf function is not allowed to invoke callback functions passed to it from the current compilation unit, directly call functions exported by the unit, or 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 (deallocator)
malloc (deallocator, ptr-index)

This attribute applies to functions.

Attribute malloc indicates that a function is 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. In addition, GCC predicts that a function with the attribute returns non-null in most cases.

Independently, the form of the attribute with one or two arguments associates deallocator as a suitable deallocation function for pointers returned from the malloc-like function. ptr-index denotes the positional argument to which when the pointer is passed in calls to deallocator has the effect of deallocating it.

Using the attribute with no arguments is designed to improve optimization by relying on the aliasing property it implies. Functions like malloc and calloc have this property because they return a pointer to uninitialized or zeroed-out, newly obtained storage. However, functions like realloc do not have this property, as they may return pointers to storage containing pointers to existing objects. Additionally, since all such functions are assumed to return null only infrequently, callers can be optimized based on that assumption.

Associating a function with a deallocator helps detect calls to mismatched allocation and deallocation functions and diagnose them under the control of options such as -Wmismatched-dealloc. It also makes it possible to diagnose attempts to deallocate objects that were not allocated dynamically, by -Wfree-nonheap-object. To indicate that an allocation function both satisfies the nonaliasing property and has a deallocator associated with it, both the plain form of the attribute and the one with the deallocator argument must be used. The same function can be both an allocator and a deallocator. Since inlining one of the associated functions but not the other could result in apparent mismatches, this form of attribute malloc is not accepted on inline functions. For the same reason, using the attribute prevents both the allocation and deallocation functions from being expanded inline.

For example, besides stating that the functions return pointers that do not alias any others, the following declarations make fclose a suitable deallocator for pointers returned from all functions except popen, and pclose as the only suitable deallocator for pointers returned from popen. The deallocator functions must be declared before they can be referenced in the attribute.

int fclose (FILE*);
int pclose (FILE*);

[[gnu::malloc, gnu::malloc (fclose, 1)]]
  FILE* fdopen (int, const char*);
[[gnu::malloc, gnu::malloc (fclose, 1)]]
  FILE* fopen (const char*, const char*);
[[gnu::malloc, gnu::malloc (fclose, 1)]]
  FILE* fmemopen(void *, size_t, const char *);
[[gnu::malloc, gnu::malloc (fclose, 1)]]
  FILE* popen (const char*, const char*);
[[gnu::malloc, gnu::malloc (fclose, 1)]]
  FILE* tmpfile (void);

The warnings guarded by -fanalyzer respect allocation and deallocation pairs marked with the malloc. In particular:

  • The analyzer emits a -Wanalyzer-mismatching-deallocation diagnostic if there is an execution path in which the result of an allocation call is passed to a different deallocator.
  • The analyzer emits a -Wanalyzer-double-free diagnostic if there is an execution path in which a value is passed more than once to a deallocation call.
  • The analyzer considers the possibility that an allocation function could fail and return null. If there are execution paths in which an unchecked result of an allocation call is dereferenced or passed to a function requiring a non-null argument, it emits -Wanalyzer-possible-null-dereference and -Wanalyzer-possible-null-argument diagnostics. If the allocator always returns non-null, use __attribute__ ((returns_nonnull)) to suppress these warnings. For example:
    char *xstrdup (const char *)
      __attribute__((malloc (free), returns_nonnull));
    
  • The analyzer emits a -Wanalyzer-use-after-free diagnostic if there is an execution path in which the memory passed by pointer to a deallocation call is used after the deallocation.
  • The analyzer emits a -Wanalyzer-malloc-leak diagnostic if there is an execution path in which the result of an allocation call is leaked (without being passed to the deallocation function).
  • The analyzer emits a -Wanalyzer-free-of-non-heap diagnostic if a deallocation function is used on a global or on-stack variable.

The analyzer assumes that deallocators can gracefully handle the null pointer. If this is not the case, the deallocator can be marked with __attribute__((nonnull)) so that -fanalyzer can emit a -Wanalyzer-possible-null-argument diagnostic for code paths in which the deallocator is called with null.

may_alias

The may_alias attribute applies to pointer type declarations.

Accesses through pointers to types with this attribute are not subject to type-based alias analysis, but are instead assumed to be able to alias any other type of objects. In the context of section 6.5 paragraph 7 of the C99 standard, an lvalue expression dereferencing such a pointer is treated like having a character type. See -fstrict-aliasing for more information on aliasing issues. This extension exists to support some vector APIs, in which pointers to one vector type are permitted to alias pointers to a different vector type.

Note that an object of a type with this attribute does not have any special semantics.

Example of use:

typedef short __attribute__ ((__may_alias__)) short_a;

int
main (void)
{
  int a = 0x12345678;
  short_a *b = (short_a *) &a;

  b[1] = 0;

  if (a == 0x12345678)
    abort();

  exit(0);
}

If you replaced short_a with short in the variable declaration, the above program would abort when compiled with -fstrict-aliasing, which is on by default at -O2 or above.

mode (mode)

This attribute can apply to a variable or type declaration.

It specifies the data type for the declaration—whichever type corresponds to the mode mode. This in effect lets you request an integer or floating-point type according to its width.

See Machine Modes in GNU Compiler Collection (GCC) Internals, for a list of the possible keywords for mode. You may also specify a mode of byte or __byte__ to indicate the mode corresponding to a one-byte integer, word or __word__ for the mode of a one-word integer, and pointer or __pointer__ for the mode used to represent pointers.

musttail

This attribute can be applied to a return statement with a return-value expression that is a function call.

It asserts that the call must be a tail call that does not allocate extra stack space, so it is safe to use tail recursion to implement long-running loops.

[[gnu::musttail]] return foo();
__attribute__((musttail)) return bar();

If the compiler cannot generate a musttail tail call it reports an error. On some targets, tail calls may not be supported at all. The musttail attribute asserts that the lifetime of automatic variables, function parameters and temporaries (unless they have non-trivial destruction) can end before the actual call instruction, and that any access to those from inside of the called function results is considered undefined behavior. Enabling -O1 or -O2 can improve the success of tail calls.

int foo (int *);
void bar (int *);
struct S { S (); ~S (); int s; };

int
baz (int *x)
{
  if (*x == 1)
    {
      int a = 42;
      /* The call is a tail call (would not be without the
         attribute).  Dereferencing the pointer in the callee is
         undefined behavior, and there is a warning emitted
         for this by default (-Wmusttail-local-addr).  */
      [[gnu::musttail]] return foo (&a);
    }
  else if (*x == 2)
    {
      int a = 42;
      bar (&a);
      /* The call is a tail call (would not be without the
         attribute).  If bar stores the pointer anywhere, dereferencing
         it in foo is undefined behavior.  There is a warning
         emitted for this with -Wextra, which implies
         -Wmaybe-musttail-local-addr.  */
      [[gnu::musttail]] return foo (nullptr);
    }
  else
    {
      S s;
      /* The s variable requires non-trivial destruction which ought
         to be performed after the foo call returns, so this is
         rejected.  */
      [[gnu::musttail]] return foo (&s.s);
    }
}

To avoid the -Wmaybe-musttail-local-addr warning in the above *x == 2 case and similar code, consider defining the maybe-escaped variables in a separate scope that ends before the return statement, if that is possible, to make it clear that the variable is not live during the call. So:

  else if (*x == 2)
    {
      {
        int a = 42;
        bar (&a);
      }
      /* The call is a tail call (would not be without the
         attribute).  If bar stores the pointer anywhere, dereferencing
         it in foo is undefined behavior even without tail call
         optimization, and there is no warning.  */
      [[gnu::musttail]] return foo (nullptr);
    }

It is not possible to avoid the warning in this way if the maybe-escaped variable is a function argument, because those are in scope for the whole function.

naked

This attribute applies to functions.

It allows the compiler to construct the requisite function declaration, while allowing the body of the function to be assembly code. The specified function does not have prologue/epilogue sequences generated by the compiler. Only basic asm statements can safely be included in naked functions (see Basic Asm — Assembler Instructions Without Operands). While using extended asm or a mixture of basic asm and C code may appear to work, they cannot be depended upon to work reliably and are not supported.

Not all targets support this attribute. Those that do include ARC, ARM, AVR, BPF, C-SKY, MCORE, MSP430, NDS32, RISC-V, RL78, RX, and x86.

no_icf

This attribute can be applied to functions or variables.

It prevents the entity from being merged with another semantically equivalent function or variable.

no_instrument_function

This attribute applies to functions.

If any of -finstrument-functions, -p, or -pg are given, profiling function calls are generated at entry and exit of most user-compiled functions. Functions with this attribute are not so instrumented.

no_profile_instrument_function

This attribute applies to functions.

The no_profile_instrument_function attribute informs the compiler that it should not process any code instrumentation for profile-feedback-based optimization code instrumentation.

no_reorder

This attribute applies to functions or variables.

Functions or variables marked no_reorder are not reordered with respect to each other or top-level assembler statements in the executable. The actual order in the program depends on the linker command line. This has a similar effect as the -fno-toplevel-reorder option, but only applies to the marked symbols.

no_sanitize ("sanitize_option")

This attribute applies to functions.

The no_sanitize attribute informs the compiler that it should not do sanitization of any option mentioned in sanitize_option. A list of values acceptable by the -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

This attribute applies to functions.

The no_sanitize_address attribute informs the compiler that it should not instrument memory accesses in the function when compiling with the -fsanitize=address option.

no_address_safety_analysis is a deprecated alias of the no_sanitize_address attribute; new code should use no_sanitize_address.

no_sanitize_coverage

This attribute applies to functions.

The no_sanitize_coverage attribute informs the compiler that it should not do coverage-guided fuzzing code instrumentation (-fsanitize-coverage).

no_sanitize_thread

This attribute applies to functions.

The no_sanitize_thread attribute informs the compiler that it should not instrument memory accesses in the function when compiling with the -fsanitize=thread option.

no_sanitize_undefined

This attribute applies to functions.

The no_sanitize_undefined attribute informs the compiler that it should not check for undefined behavior in the function when compiling with the -fsanitize=undefined option.

no_split_stack

This attribute applies to functions.

If -fsplit-stack is given, functions have a small prologue which decides whether to split the stack. Functions with the 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

This attribute applies to functions.

This attribute locally overrides the -fstack-limit-register and -fstack-limit-symbol command-line options; it has the effect of disabling stack limit checking in the function it applies to.

no_stack_protector

This attribute applies to functions.

It prevents GCC from generating stack protection code for the function.

noclone

This attribute applies to functions.

This attribute prevents a function from being considered for cloning—a mechanism that produces specialized copies of functions and which is (currently) performed by interprocedural constant propagation.

noinit

This attribute applies to variables.

Variables with the noinit attribute are not initialized by the C runtime startup code, or the program loader. Not initializing data in this way can reduce program startup times.

This attribute is specific to ELF targets and relies on the linker script to place sections with the .noinit prefix in the right location.

noinline

This attribute applies to functions.

It prevents the function from being considered for inlining. It also disables some other interprocedural optimizations; it’s preferable to use the more comprehensive noipa attribute instead if that is your goal.

Even if a function is declared with the noinline attribute, there are optimizations other than inlining that can cause calls to be optimized away if it does not have side effects, although the function call is live. To keep such calls from being optimized away, put

asm ("");

(see Extended Asm - Assembler Instructions with C Expression Operands) in the called function, to serve as a special side effect.

noipa

This attribute applies to functions.

It disables interprocedural optimizations between the function with this attribute and its callers, as if the body of the function is not available when optimizing callers and the callers are unavailable when optimizing the body. This attribute implies 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.

nonnull
nonnull (arg-index, …)

The nonnull attribute may be applied to a function that takes at least one argument of a pointer type.

It indicates that the referenced arguments must be non-null pointers. For instance, the declaration:

extern void *
my_memcpy (void *dest, const void *src, size_t len)
        __attribute__((nonnull (1, 2)));

informs the compiler that, in calls to my_memcpy, arguments dest and src must be non-null.

The attribute has an effect both on functions calls and function definitions.

For function calls:

  • 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. See Options to Request or Suppress Warnings.
  • The -fisolate-erroneous-paths-attribute option can be specified to have GCC transform calls with null arguments to non-null functions into traps. See Options That Control Optimization.
  • The compiler may also perform optimizations based on the knowledge that certain function arguments cannot be null. These optimizations can be disabled by the -fno-delete-null-pointer-checks option. See Options That Control Optimization.

For function definitions:

  • If the compiler determines that a function parameter that is marked with nonnull is compared with null, and -Wnonnull-compare option is enabled, a warning is issued. See Options to Request or Suppress Warnings.
  • The compiler may also perform optimizations based on the knowledge that nonnull parameters cannot be null. This can currently not be disabled other than by removing the nonnull attribute.

If no arg-index 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));
nonnull_if_nonzero (arg-index, arg2-index)
nonnull_if_nonzero (arg-index, arg2-index, arg3-index)

This attribute may be applied to a function that takes at least one argument of a pointer type.

The nonnull_if_nonzero attribute is a conditional version of the nonnull attribute. It has two or three arguments; the first argument shall be argument index of a pointer argument which must be in some cases non-null and the second argument shall be argument index of an integral argument (other than boolean). If the integral argument is zero, the pointer argument can be null, if it is non-zero, the pointer argument must not be null. If three arguments are provided, the third argument shall be argument index of another integral argument (other than boolean) and the pointer argument can be null if either of the integral arguments are zero and if both are non-zero, the pointer argument must not be null.

[[gnu::nonnull (1, 2)]]
extern void *
my_memcpy (void *dest, const void *src, size_t len);

[[gnu::nonnull_if_nonzero (1, 3),
  gnu::nonnull_if_nonzero (2, 3)]]
extern void *
my_memcpy2 (void *dest, const void *src, size_t len);

[[gnu::nonnull (4),
  gnu::nonnull_if_nonzero (1, 2, 3)]]
extern size_t
my_fread (void *buf, size_t size, size_t count, FILE *stream);

With these declarations, it is invalid to call my_memcpy (NULL, NULL, 0); or to call my_memcpy2 (NULL, NULL, 4); or to call my_fread(buf, 0, 0, NULL); or to call my_fread(NULL, 1, 1, stream); but it is valid to call my_memcpy2 (NULL, NULL, 0); or my_fread(NULL, 0, 0, stream); or my_fread(NULL, 0, 1, stream); or my_fread(NULL, 1, 0, stream);. This attribute should be used on declarations which have e.g. an exception for zero sizes, in which case null may be passed.

nonstring

This attribute applies to variables or members of a struct, union, or class that have type array of char, signed char, or unsigned char, or pointer to such a type.

The nonstring attribute specifies that an object or member of such a type is intended to store character arrays that do not necessarily contain a terminating NUL. This is useful in detecting uses of such arrays or pointers with functions that expect NUL-terminated strings, and to avoid warnings when such an array or pointer is used as an argument to a bounded string manipulation function such as strncpy. For example, without the attribute, GCC issues a warning for the strncpy call below because it may truncate the copy without appending the terminating NUL character. Using the attribute makes it possible to suppress the warning. However, when the array is declared with the attribute the call to strlen is diagnosed because when the array doesn’t contain a NUL-terminated string the call is undefined. To copy, compare, or search non-string character arrays use the memcpy, memcmp, memchr, and other functions that operate on arrays of bytes. In addition, calling strnlen and strndup with such arrays is safe provided a suitable bound is specified, and not diagnosed.

struct Data
{
  char name [32] __attribute__ ((nonstring));
};

int f (struct Data *pd, const char *s)
{
  strncpy (pd->name, s, sizeof pd->name);
  ...
  return strlen (pd->name);   // unsafe, gets a warning
}
noplt

This attribute applies to functions.

The 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.  */
[[gnu::noplt]] int foo ();

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

This attribute applies to functions.

A few standard library functions, such as 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 does 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.

In order to preserve backtraces, GCC never turns calls to noreturn functions into tail calls.

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

This attribute applies to functions.

The 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.

null_terminated_string_arg
null_terminated_string_arg (N)

The null_terminated_string_arg attribute may be applied to a function that takes a char * or const char * at referenced argument N.

It indicates that the passed argument must be a C-style null-terminated string. Specifically, the presence of the attribute implies that, if the pointer is non-null, the function may scan through the referenced buffer looking for the first zero byte.

In particular, when the analyzer is enabled (via -fanalyzer), if the pointer is non-null, it will simulate scanning for the first zero byte in the referenced buffer, and potentially emit -Wanalyzer-use-of-uninitialized-value or -Wanalyzer-out-of-bounds on improperly terminated buffers.

For example, given the following:

char *example_1 (const char *p)
  __attribute__((null_terminated_string_arg (1)));

the analyzer checks that any non-null pointers passed to the function are validly terminated.

If the parameter must be non-null, it is appropriate to use both this attribute and the attribute nonnull, such as in:

extern char *example_2 (const char *p)
  __attribute__((null_terminated_string_arg (1),
                 nonnull (1)));

See the nonnull attribute for more information and caveats.

If the pointer argument is also referred to by an access attribute on the function with access-mode either read_only or read_write and the latter attribute has the optional size-index argument referring to a size argument, this expresses the maximum size of the access. For example, given:

[[gnu::null_terminated_string_arg (1),
  gnu::access (read_only, 1, 2),
  gnu::nonnull (1)]]
extern char *example_fn (const char *p, size_t n);

the analyzer requires the first parameter to be non-null, and either be validly null-terminated, or validly readable up to the size specified by the second parameter.

objc_nullability (nullability kind) (Objective-C and Objective-C++ only)

This attribute applies to pointer variables only.

It allows marking the pointer with one of four possible values describing the conditions under which the pointer might have a nil value. In most cases, the attribute is intended to be an internal representation for property and method nullability (specified by language keywords); it is not recommended to use it directly.

When nullability kind is "unspecified" or 0, nothing is known about the conditions in which the pointer might be nil. Making this state specific serves to avoid false positives in diagnostics.

When nullability kind is "nonnull" or 1, the pointer has no meaning if it is nil and thus the compiler is free to emit diagnostics if it can be determined that the value will be nil.

When nullability kind is "nullable" or 2, the pointer might be nil and carry meaning as such.

When nullability kind is "resettable" or 3 (used only in the context of property attribute lists) this describes the case in which a property setter may take the value nil (which perhaps causes the property to be reset in some manner to a default) but for which the property getter will never validly return nil.

objc_root_class (Objective-C and Objective-C++ only)

This attribute applies to Objective-C and Objective-C++ classes.

It marks the class as being a root class, and thus allows the compiler to elide any warnings about a missing superclass and to make additional checks for mandatory methods as needed.

optimize (level, …)
optimize (string, …)

This attribute applies to functions.

The optimize attribute is used to specify that the function is to be compiled with different optimization options than specified on the command line. The optimize attribute arguments of a function behave as if appended to the command-line.

Valid arguments are constant non-negative integers and strings. Each numeric argument specifies an optimization level. Each string argument consists of one or more comma-separated substrings. Each substring that begins with the letter O refers to an optimization option such as -O0 or -Os. Other substrings are taken as suffixes to the -f prefix jointly forming the name of an optimization option. See Options That Control Optimization.

#pragma GCC optimize’ can be used to set optimization options for more than one function. See Function Specific Option Pragmas, for details about the pragma.

Providing multiple strings as arguments separated by commas to specify multiple options is equivalent to separating the option suffixes with a comma (‘,’) within a single string. Spaces are not permitted within the strings.

Not every optimization option that starts with the -f prefix specified by the attribute necessarily has an effect on the function. The optimize attribute should be used for debugging purposes only. It is not suitable in production code.

packed

This attribute can be attached to a struct, union, or C++ class definition, to a member of one, or to an enum definition.

The packed attribute on a structure member specifies that the member should have the smallest possible alignment—one bit for a bit-field and one byte otherwise, unless a larger value is specified with the aligned attribute. The attribute does not apply to non-member objects.

For example in the structure below, the member array x is packed so that it immediately follows a with no intervening padding:

struct foo
{
  char a;
  int x[2] __attribute__ ((packed));
};

Note: The 4.1, 4.2 and 4.3 series of GCC ignored the packed attribute on bit-fields of type char. This was fixed in GCC 4.4 but the change could lead to differences in the structure layout. See the documentation of -Wpacked-bitfield-compat for more information.

Applied to a struct, union, or C++ class definition as a whole, it specifies that each of its members (other than zero-width bit-fields) is placed to minimize the memory required. This is equivalent to specifying the packed attribute on each of the members.

In the following example struct my_packed_struct’s members are packed closely together, but the internal layout of its s member is not packed—to do that, struct my_unpacked_struct needs to be packed too.

struct my_unpacked_struct
{
  char c;
  int i;
};

struct [[gnu::__packed__]] my_packed_struct
{
  char c;
  int  i;
  struct my_unpacked_struct s;
  };

When attached to an enum indicates that the smallest integral type should be used to represent the type. Specifying the -fshort-enums flag on the command line is equivalent to specifying the packed attribute on all enum definitions.

You may only specify the packed attribute on the definition of an enum, struct, union, or class, not on a typedef that does not also define the enumerated type, structure, union, or class.

patchable_function_entry

This attribute applies to functions.

In case the target’s text segment can be made writable at run time by any means, padding the function entry with a number of NOPs can be used to provide a universal tool for instrumentation.

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.

persistent

This attribute applies to variables.

Any variables with the persistent attribute are not initialized by the C runtime startup code, but instead are initialized by the program loader. This enables the value of the variable to persist between processor resets.

This attribute is specific to ELF targets and relies on the linker script to place the sections with the .persistent prefix in the right location. Specifically, some type of non-volatile, writable memory is required.

pure

This attribute applies to functions.

Calls to functions that have no observable effects on the state of the program other than to return a value may lend themselves to optimizations such as common subexpression elimination. Declaring such functions with the pure attribute allows GCC to avoid emitting some calls in repeated invocations of the function with the same argument values.

The pure attribute prohibits a function from modifying the state of the program that is observable by means other than inspecting the function’s return value. However, functions declared with the pure attribute can safely read any non-volatile objects, and modify the value of objects in a way that does not affect their return value or the observable state of the program.

For example,

int hash (char *) __attribute__ ((pure));

tells GCC that subsequent calls to the function hash with the same string can be replaced by the result of the first call provided the state of the program observable by hash, including the contents of the array itself, does not change in between. Even though hash takes a non-const pointer argument it must not modify the array it points to, or any other object whose value the rest of the program may depend on. However, the caller may safely change the contents of the array between successive calls to the function (doing so disables the optimization). The restriction also applies to member objects referenced by the this pointer in C++ non-static member functions.

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 consecutive calls (such as the standard C feof function in a multithreading environment).

The pure attribute imposes similar but looser restrictions on a function’s definition than the const attribute: pure allows the function to read any non-volatile memory, even if it changes in between successive invocations of the function. Declaring the same function with both the pure and the const attribute is diagnosed. Because a pure function cannot have any observable side effects it does not make sense for such a function to return void. Declaring such a function is diagnosed.

reproducible

This attribute applies to function types.

This attribute is a GNU counterpart of the C23 [[reproducible]] attribute, used to specify function pointers to effectless and idempotent functions according to the C23 definition.

Unlike the standard C23 attribute it can be also specified in attributes which appertain to function declarations and applies to the their function type even in that case.

Reproducible functions without pointer or reference arguments or which do not modify objects referenced by those pointer/reference arguments are similar to functions with the pure attribute, except that pure attribute also requires finiteness. So, both functions with pure and with reproducible attributes can be optimized by common subexpression elimination if the global state or anything reachable through the pointer/reference arguments isn’t modified, but only functions with pure attribute can be optimized by dead code elimination if their result is unused or is used only by dead code. Reproducible functions without pointer or reference arguments with void return type are diagnosed because they can’t store any results and don’t have other observable side-effects either.

Reproducible functions with pointer or reference arguments can store additional results through those pointers or references or references to pointers.

retain

This attribute applies to functions and variables.

For ELF targets that support the GNU or FreeBSD OSABIs, this attribute protects the function or variable it applies to from linker garbage collection. To support this behavior, functions and variables that have not been placed in specific sections (e.g. by the section attribute, or the -ffunction-sections or -fdata-sections options) are placed in new, unique sections.

This additional functionality requires Binutils version 2.36 or later.

returns_nonnull

This attribute applies to functions returning a pointer type.

The returns_nonnull attribute specifies that the function return value should be a non-null pointer. For instance, the declaration:

[[gnu::returns_nonnull]]
extern void *mymalloc (size_t len);

lets the compiler optimize callers based on the knowledge that the return value will never be null.

returns_twice

This attribute applies to functions.

The 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.

scalar_storage_order ("endianness")

This attribute applies to a union or struct.

It sets the storage order, aka endianness, of the scalar fields of the type, as well as the array fields whose component is scalar. The supported endiannesses are big-endian and little-endian. The attribute has no effects on fields which are themselves a union, a struct or an array whose component is a union or a struct, and it is possible for these fields to have a different scalar storage order than the enclosing type.

Note that neither pointer nor vector fields are considered scalar fields in this context, so the attribute has no effects on these fields.

This attribute is supported only for targets that use a uniform default scalar storage order (fortunately, most of them), i.e. targets that store the scalars either all in big-endian or all in little-endian.

Additional restrictions are enforced for types with the reverse scalar storage order with regard to the scalar storage order of the target:

  • Taking the address of a scalar field of a union or a struct with reverse scalar storage order is not permitted and yields an error.
  • Taking the address of an array field, whose component is scalar, of a union or a struct with reverse scalar storage order is permitted but yields a warning, unless -Wno-scalar-storage-order is specified.
  • Taking the address of a union or a struct with reverse scalar storage order is permitted.

These restrictions exist because the storage order attribute is lost when the address of a scalar or the address of an array with scalar component is taken, so storing indirectly through this address generally does not work. The second case is nevertheless allowed to be able to perform a block copy from or to the array.

Moreover, the use of type punning or aliasing to toggle the storage order is not supported; that is to say, if a given scalar object can be accessed through distinct types that assign a different storage order to it, then the behavior is undefined.

section ("section-name")

This attribute applies to functions and variables.

Normally, the compiler places the code it generates in the text section, and variables in data or bss. Sometimes, however, you need additional sections, or you need certain particular functions or variables to appear in special sections. The section attribute specifies that the function or variable it applies to lives in a particular section. For example, the declaration:

extern void foobar (void) __attribute__ ((section ("bar")));

puts the function foobar in the bar section.

Here’s a more complicated example:

struct duart a __attribute__ ((section ("DUART_A"))) = { 0 };
struct duart b __attribute__ ((section ("DUART_B"))) = { 0 };
char stack[10000] __attribute__ ((section ("STACK"))) = { 0 };
int init_data __attribute__ ((section ("INITDATA")));

main()
{
  /* Initialize stack pointer */
  init_sp (stack + sizeof (stack));

  /* Initialize initialized data */
  memcpy (&init_data, &data, &edata - &data);

  /* Turn on the serial ports */
  init_duart (&a);
  init_duart (&b);
}

Use the section attribute with global variables and not local variables, as shown in the example.

You may use the section attribute with initialized or uninitialized global variables but the linker requires each object be defined once, with the exception that uninitialized variables tentatively go in the common (or bss) section and can be multiply “defined”. Using the section attribute changes what section the variable goes into and may cause the linker to issue an error if an uninitialized variable has multiple definitions. You can force a variable to be initialized with the -fno-common flag or the nocommon attribute.

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
sentinel (position)

This attribute applies to functions.

It indicates that an argument in a call to the function is expected to be an explicit NULL. The attribute is only valid on variadic functions. By default, the sentinel is expected to be the last argument of the function call. If the optional position argument is specified to the attribute, the sentinel must be located at position counting backwards from the end of the argument list.

[[gnu::sentinel]]’ is equivalent to ‘[[gnu::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 object pointer type. If your system defines the NULL macro with an integer type then you need to add an explicit cast. During installation GCC replaces the system <stddef.h> header with a copy that redefines NULL appropriately.

The warnings for missing or incorrect sentinels are enabled with -Wformat.

simd
simd("mask")

This attribute applies to functions.

It enables creation of one or more function versions that can process multiple arguments using SIMD instructions from a single invocation. Specifying this attribute allows compiler to assume that such versions are available at link time (provided in the same or another translation unit). Generated versions are target-dependent and described in the corresponding Vector ABI document. For x86_64 target this document can be found here.

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

This attribute applies to functions.

It adds stack protection code to the function it applies to if flags -fstack-protector, -fstack-protector-strong or -fstack-protector-explicit are set.

strict_flex_array (level)

The strict_flex_array attribute can be attached to the trailing array field of a structure.

It controls when to treat the trailing array field of a structure as a flexible array member for the purposes of accessing the elements of such an array. level must be an integer between 0 to 3.

level=0 is the least strict level, all trailing arrays of structures are treated as flexible array members. level=3 is the strictest level, only when the trailing array is declared as a flexible array member per C99 standard onwards (‘[]’), it is treated as a flexible array member.

There are two more levels in between 0 and 3, which are provided to support older code that uses the GCC zero-length array extension (‘[0]’) or one-element array as flexible array members (‘[1]’). When level is 1, the trailing array is treated as a flexible array member when it is declared as either ‘[]’, ‘[0]’, or ‘[1]’. When level is 2, the trailing array is treated as a flexible array member when it is declared as either ‘[]’, or ‘[0]’.

This attribute can be used with or without the -fstrict-flex-arrays command-line option. When both the attribute and the option are present at the same time, the level of the strictness for the specific trailing array field is determined by the attribute.

The strict_flex_array attribute interacts with the -Wstrict-flex-arrays option. See Options to Request or Suppress Warnings, for more information.

strub

This attribute applies to types, and may also appear in variable and function declarations.

The strub attribute defines stack-scrubbing properties of functions and variables, so that functions that access sensitive data can have their stack frames zeroed out upon returning or propagating exceptions. This may be enabled explicitly, by selecting certain strub modes for specific functions, or implicitly, by means of strub variables.

Being a type attribute, it attaches to types, even when specified in function and variable declarations. When applied to function types, it takes an optional string argument. When applied to a pointer-to-function type, if the optional argument is given, it gets propagated to the function type.

/* A strub variable.  */
int __attribute__ ((strub)) var;
/* A strub variable that happens to be a pointer.  */
__attribute__ ((strub)) int *strub_ptr_to_int;
/* A pointer type that may point to a strub variable.  */
typedef int __attribute__ ((strub)) *ptr_to_strub_int_type;

/* A declaration of a strub function.  */
extern int __attribute__ ((strub)) foo (void);
/* A pointer to that strub function.  */
int __attribute__ ((strub ("at-calls"))) (*ptr_to_strub_fn)(void) = foo;

A function associated with at-calls strub mode (strub("at-calls"), or just strub) undergoes interface changes. Its callers are adjusted to match the changes, and to scrub (overwrite with zeros) the stack space used by the called function after it returns. The interface change makes the function type incompatible with an unadorned but otherwise equivalent type, so every declaration and every type that may be used to call the function must be associated with this strub mode.

A function associated with internal strub mode (strub("internal")) retains an unmodified, type-compatible interface, but it may be turned into a wrapper that calls the wrapped body using a custom interface. The wrapper then scrubs the stack space used by the wrapped body. Though the wrapped body has its stack space scrubbed, the wrapper does not, so arguments and return values may remain unscrubbed even when such a function is called by another function that enables strub. This is why, when compiling with -fstrub=strict, a strub context is not allowed to call internal strub functions.

/* A declaration of an internal-strub function.  */
extern int __attribute__ ((strub ("internal"))) bar (void);

int __attribute__ ((strub))
baz (void)
{
  /* Ok, foo was declared above as an at-calls strub function.  */
  foo ();
  /* Not allowed in strict mode, otherwise allowed.  */
  bar ();
}

An automatically-allocated variable associated with the strub attribute causes the (immediately) enclosing function to have strub enabled.

A statically-allocated variable associated with the strub attribute causes functions that read it, through its strub data type, to have strub enabled. Reading data by dereferencing a pointer to a strub data type has the same effect. Note: The attribute does not carry over from a composite type to the types of its components, so the intended effect may not be obtained with non-scalar types.

When selecting a strub-enabled mode for a function that is not explicitly associated with one, because of strub variables or data pointers, the function must satisfy internal mode viability requirements (see below), even when at-calls mode is also viable and, being more efficient, ends up selected as an optimization.

/* zapme is implicitly strub-enabled because of strub variables.
   Optimization may change its strub mode, but not the requirements.  */
static int
zapme (int i)
{
  /* A local strub variable enables strub.  */
  int __attribute__ ((strub)) lvar;
  /* Reading strub data through a pointer-to-strub enables strub.  */
  lvar = * (ptr_to_strub_int_type) &i;
  /* Writing to a global strub variable does not enable strub.  */
  var = lvar;
  /* Reading from a global strub variable enables strub.  */
  return var;
}

A strub context is the body (as opposed to the interface) of a function that has strub enabled, be it explicitly, by at-calls or internal mode, or implicitly, due to strub variables or command-line options.

A function of a type associated with the disabled strub mode (strub("disabled") does not have its own stack space scrubbed. Such functions cannot be called from within strub contexts.

In order to enable a function to be called from within strub contexts without having its stack space scrubbed, associate it with the callable strub mode (strub("callable")).

When a function is not assigned a strub mode, explicitly or implicitly, the mode defaults to callable, except when compiling with -fstrub=strict, that causes strub mode to default to disabled.

[[gnu::strub("callable")]] extern int bac (void);
[[gnu::strub("disabled")]] extern int bad (void);
 /* Implicitly disabled with -fstrub=strict, otherwise callable.  */
extern int bah (void);

[[gnu::strub]]
int
bal (void)
{
  /* Not allowed, bad is not strub-callable.  */
  bad ();
  /* Ok, bac is strub-callable.  */
  bac ();
  /* Not allowed with -fstrub=strict, otherwise allowed.  */
  bah ();
}

Function types marked callable and disabled are not mutually compatible types, but the underlying interfaces are compatible, so it is safe to convert pointers between them, and to use such pointers or alternate declarations to call them. Interfaces are also interchangeable between them and internal (but not at-calls!), but adding internal to a pointer type will not cause the pointed-to function to perform stack scrubbing.

void __attribute__ ((strub))
bap (void)
{
  /* Assign a callable function to pointer-to-disabled.
     Flagged as not quite compatible with -Wpedantic.  */
  int __attribute__ ((strub ("disabled"))) (*d_p) (void) = bac;
  /* Not allowed: calls disabled type in a strub context.  */
  d_p ();

  /* Assign a disabled function to pointer-to-callable.
     Flagged as not quite compatible with -Wpedantic.  */
  int __attribute__ ((strub ("callable"))) (*c_p) (void) = bad;
  /* Ok, safe.  */
  c_p ();

  /* Assign an internal function to pointer-to-callable.
     Flagged as not quite compatible with -Wpedantic.  */
  c_p = bar;
  /* Ok, safe.  */
  c_p ();

  /* Assign an at-calls function to pointer-to-callable.
     Flaggged as incompatible.  */
  c_p = bal;
  /* The call through an interface-incompatible type will not use the
     modified interface expected by the at-calls function, so it is
     likely to misbehave at runtime.  */
  c_p ();
}

Strub contexts are never inlined into non-strub contexts. When an internal-strub function is split up, the wrapper can often be inlined, but the wrapped body never is. A function marked as always_inline, even if explicitly assigned internal strub mode, will not undergo wrapping, so its body gets inlined as required.

inline int __attribute__ ((strub ("at-calls")))
inl_atc (void)
{
  /* This body may get inlined into strub contexts.  */
}

inline int __attribute__ ((strub ("internal")))
inl_int (void)
{
  /* This body NEVER gets inlined, though its wrapper may.  */
}

inline int __attribute__ ((strub ("internal"), always_inline))
inl_int_ali (void)
{
  /* No internal wrapper, so this body ALWAYS gets inlined,
     but it cannot be called from non-strub contexts.  */
}

void __attribute__ ((strub ("disabled")))
bat (void)
{
  /* Not allowed, cannot inline into a non-strub context.  */
  inl_int_ali ();
}

Some -fstrub=* command-line options enable strub modes implicitly where viable. A strub mode is only viable for a function if the function is eligible for that mode, and if other conditions, detailed below, are satisfied. If it’s not eligible for a mode, attempts to explicitly associate it with that mode are rejected with an error message. If it is eligible, that mode may be assigned explicitly through this attribute, but implicit assignment through command-line options may involve additional viability requirements.

A function is ineligible for at-calls strub mode if a different strub mode is explicitly requested, if attribute noipa is present, or if it calls __builtin_apply_args. At-calls strub mode, if not requested through the function type, is only viable for an eligible function if the function is not visible to other translation units, if it doesn’t have its address taken, and if it is never called with a function type overrider.

/* bar is eligible for at-calls strub mode,
   but not viable for that mode because it is visible to other units.
   It is eligible and viable for internal strub mode.  */
void bav () {}

/* setp is eligible for at-calls strub mode,
   but not viable for that mode because its address is taken.
   It is eligible and viable for internal strub mode.  */
void setp (void) { static void (*p)(void); = setp; }

A function is ineligible for internal strub mode if a different strub mode is explicitly requested, or if attribute noipa is present. For an always_inline function, meeting these requirements is enough to make it eligible. Any function that has attribute noclone, that uses such extensions as non-local labels, computed gotos, alternate variable argument passing interfaces, __builtin_next_arg, or __builtin_return_address, or that takes too many (about 64Ki) arguments is ineligible, unless it is always_inline. For internal strub mode, all eligible functions are viable.

/* flop is not eligible, thus not viable, for at-calls strub mode.
   Likewise for internal strub mode.  */
__attribute__ ((noipa)) void flop (void) {}

/* flip is eligible and viable for at-calls strub mode.
   It would be ineligible for internal strub mode, because of noclone,
   if it weren't for always_inline.  With always_inline, noclone is not
   an obstacle, so it is also eligible and viable for internal strub
   mode.  */
inline __attribute__ ((noclone, always_inline)) void flip (void) {}
symver ("name2@nodename")

This attribute applies to functions.

On ELF targets this attribute creates a symbol version. The name2 part of the parameter is the actual name of the symbol by which it will be externally referenced. The nodename portion should be the name of a node specified in the version script supplied to the linker when building a shared library. The versioned symbol must be defined and must be exported with default visibility.

This example produces a .symver foo_v1, foo@VERS_1 directive in the assembler output.:

[[gnu::__symver__ ("foo@VERS_1")]] int
foo_v1 (void)
{
}

You can also define multiple versions for a given symbol (starting from binutils 2.35):

[[gnu::__symver__ ("foo@VERS_2"), gnu::__symver__ ("foo@VERS_3")]]
int symver_foo_v1 (void)
{
}

This example creates a symbol name symver_foo_v1 which will be version VERS_2 and VERS_3 of foo.

If you have an older release of binutils, then you need to use a symbol alias:

__attribute__ ((__symver__ ("foo@VERS_2")))
int foo_v1 (void)
{
  return 0;
}

__attribute__ ((__symver__ ("foo@VERS_3")))
__attribute__ ((alias ("foo_v1")))
int symver_foo_v1 (void);

Finally, if the parameter is "name2@@nodename", then in addition to creating a symbol version (as if "name2@nodename" was used) the version is also used to resolve name2 by the linker.

tainted_args

This attribute applies to functions.

The tainted_args attribute is used to specify that a function is called in a way that requires sanitization of its arguments, such as a system call in an operating system kernel. Such a function can be considered part of the “attack surface” of the program. The attribute can be used both on function declarations, and on field declarations containing function pointers. In the latter case, any function used as an initializer of such a callback field is treated as being called with tainted arguments.

The analyzer pays particular attention to such functions when -fanalyzer is supplied, potentially issuing warnings guarded by -Wanalyzer-tainted-allocation-size, -Wanalyzer-tainted-array-index, -Wanalyzer-tainted-divisor, -Wanalyzer-tainted-offset, and -Wanalyzer-tainted-size.

target (string, …)

This attribute applies to functions.

Multiple target back ends implement the target attribute to specify that a function is to be compiled with different target options than specified on the command line. The original target command-line options are ignored. One or more strings can be provided as arguments. Each string consists of one or more comma-separated suffixes to the -m prefix jointly forming the name of a machine-dependent option. See Target-Specific Options.

The target attribute can be used for instance to have a function compiled with a different ISA (instruction set architecture) than the default. ‘#pragma GCC target’ can be used to specify target-specific options for more than one function. See Function Specific Option Pragmas, for details about the 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")));

Providing multiple strings as arguments separated by commas to specify multiple options is equivalent to separating the option suffixes with a comma (‘,’) within a single string. Spaces are not permitted within the strings.

The options supported are specific to each target; refer to x86 Attributes, PowerPC Attributes, ARM Attributes, AArch64 Attributes, LoongArch Attributes, and S/390 Attributes for details.

On targets supporting target function multiversioning (x86), when using C++, you can declare multiple functions with the same signatures but different target attribute values, and the correct version is chosen by the dynamic linker. In the example below, two function versions are produced with differing mangling. Additionally an ifunc resolver is created to select the correct version to populate the func symbol.

int func (void) __attribute__ ((target ("arch=core2"))) { return 1; }
int func (void) __attribute__ ((target ("sse3"))) { return 2; }

Declarations annotated with target cannot be used in combination with declarations annotated with target_clones in a single multiversioned function definition.

See Function Multiversioning for more details.

target_version (option)

This attribute applies to functions.

On targets with target_version function multiversioning (AArch64, LoongArch, and RISC-V) in C or C++, you can declare multiple functions with target_version or target_clones attributes to define a function version set.

See Function Multiversioning for more details.

target_clones (options)

This attribute applies to functions.

The 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.

For the x86 and PowerPC targets, the supported options and restrictions are the same as for the target attribute. For LoongArch, See LoongArch Attributes, for details of the syntax.

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.

target_clones works similarly for targets that support the target_version attribute (AArch64, LoongArch, and RISC-V). The attribute takes multiple arguments, and generates a versioned clone for each. A function annotated with target_clones is equivalent to the same function duplicated for each valid version string in the argument, where each version is instead annotated with target_version. This means that a target_clones annotated function definition can be used in combination with target_version annotated functions definitions and other target_clones annotated function definitions.

For these targets the supported options and restrictions are the same as for the target_version attribute.

See Function Multiversioning for more details.

tls_model ("tls_model")

This attribute applies to variables.

The tls_model variable attribute sets thread-local storage model (see Thread-Local Storage) of a particular __thread variable, overriding -ftls-model= command-line switch on a per-variable basis. The tls_model argument should be one of global-dynamic, local-dynamic, initial-exec or local-exec.

Not all targets support this attribute.

transparent_union

This attribute applies to union type definitions.

It indicates that any function parameter having that union type causes calls to that function to be treated in a special way.

First, the argument corresponding to a transparent union type can be of any type in the union; no cast is required. Also, if the union contains a pointer type, the corresponding argument can be a null pointer constant or a void pointer expression; and if the union contains a void pointer type, the corresponding argument can be any pointer expression. If the union member type is a pointer, qualifiers like const on the referenced type must be respected, just as with normal pointer conversions.

Second, the argument is passed to the function using the calling conventions of the first member of the transparent union, not the calling conventions of the union itself. All members of the union must have the same machine representation; this is necessary for this argument passing to work properly.

Transparent unions are designed for library functions that have multiple interfaces for compatibility reasons. For example, suppose the wait function must accept either a value of type int * to comply with POSIX, or a value of type union wait * to comply with the 4.1BSD interface. If wait’s parameter were void *, wait would accept both kinds of arguments, but it would also accept any other pointer type and this would make argument type checking less useful. Instead, <sys/wait.h> might define the interface as follows:

typedef union __attribute__ ((__transparent_union__))
  {
    int *__ip;
    union wait *__up;
  } wait_status_ptr_t;

pid_t wait (wait_status_ptr_t);

This interface allows either int * or union wait * arguments to be passed, using the int * calling convention. The program can call wait with arguments of either type:

int w1 () { int w; return wait (&w); }
int w2 () { union wait w; return wait (&w); }

With this interface, wait’s implementation might look like this:

pid_t wait (wait_status_ptr_t p)
{
  return waitpid (-1, p.__ip, 0);
}
unavailable
unavailable (msg)

The unavailable attribute can apply to functions, variables, types, or enumerators.

It results in an error if the entity it applies to is used anywhere in the source file. This is useful when identifying entities that have been removed from a particular variation of an interface. Other than emitting an error rather than a warning, the unavailable attribute behaves in the same manner as deprecated.

uninitialized

This variable applies to variables with automatic storage.

It means that the variable should not be automatically initialized by the compiler when the option -ftrivial-auto-var-init presents.

With the option -ftrivial-auto-var-init, all the automatic variables that do not have explicit initializers are initialized by the compiler. These additional compiler initializations might incur run-time overhead, sometimes dramatically. This attribute can be used to mark some variables to be excluded from such automatic initialization in order to reduce runtime overhead.

This attribute has no effect when the option -ftrivial-auto-var-init is not present.

unsequenced

This type attribute can appear on both function declarations and declarations of function types.

It is a GNU counterpart of the C23 [[unsequenced]] attribute, used to specify function pointers to effectless, idempotent, stateless and independent functions according to the C23 definition.

Unlike the standard C23 attribute it can be also specified in attributes which appertain to function declarations and applies to the their function type even in that case.

Unsequenced functions without pointer or reference arguments are similar to functions with the const attribute, except that const attribute also requires finiteness. So, both functions with const and with unsequenced attributes can be optimized by common subexpression elimination, but only functions with const attribute can be optimized by dead code elimination if their result is unused or is used only by dead code. Unsequenced functions without pointer or reference arguments with void return type are diagnosed because they can’t store any results and don’t have other observable side-effects either.

Unsequenced functions with pointer or reference arguments can inspect objects through the passed pointers or references or references to pointers or can store additional results through those pointers or references or references to pointers.

The unsequenced attribute imposes greater restrictions than the similar reproducible attribute and fewer restrictions than the const attribute, so during optimization const has precedence over unsequenced which has precedence over reproducible.

unused

This attribute can be attached to a function, variable, structure field, type declaration, or label.

When applied to a function, variable, structure field, or label it means that the entity it applies to is meant to be possibly unused. It suppresses GCC’s normal warnings about unused entities.

When attached to a type (including a union or a struct), this attribute means that variables of that type are meant to appear possibly unused. GCC does not produce a warning for any variables of that type, even if the variable appears to do nothing. This is often the case with lock or thread classes, which are usually defined and then not referenced, but contain constructors and destructors that have nontrivial bookkeeping functions.

The unused label attribute is intended for program-generated code that may contain unused labels, but which is compiled with -Wall. It is not normally appropriate to use it in human-written code, though it could be useful in cases where the code that jumps to the label is contained within an #ifdef conditional.

used

The used attribute applies to functions and variables.

When attached to a function, this attribute means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.

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.

This attribute, attached to a variable with static storage, means that the variable must be emitted even if it appears that the variable is not referenced.

When applied to a static data member of a C++ class template, the attribute also means that the member is instantiated if the class itself is instantiated.

vector_size (bytes)

The vector_size attribute can be attached to type, variable, and function declarations.

When attached to a variable declaration, it applies to the type of the variable; when attached to a function declaration, it applies to the return type.

This attribute specifies the vector size for the type, measured in bytes. The type to which it applies is known as the base type. The bytes argument must be a positive power-of-two multiple of the base type size. For example, the following declarations using the legacy attribute syntax:

typedef __attribute__ ((vector_size (32))) int int_vec32_t ;
typedef __attribute__ ((vector_size (32))) int* int_vec32_ptr_t;
typedef __attribute__ ((vector_size (32))) int int_vec32_arr3_t[3];

or, alternatively, these declarations using the standard syntax:

typedef int int_vec32_t [[gnu::vector_size (32)]];
typedef int * int_vec32_ptr_t [[gnu::vector_size (32)]];
typedef int int_vec32_arr3_t[3] [[gnu::vector_size (32)]];

both define int_vec32_t to be a 32-byte vector type composed of int sized units. With int having a size of 4 bytes, the type defines a vector of eight units, four bytes each. The mode of variables of type int_vec32_t is V8SI. int_vec32_ptr_t is then defined to be a pointer to such a vector type, and int_vec32_arr3_t to be an array of three such vectors.

Here is an example involving a function declaration:

__attribute__ ((vector_size (16))) float get_flt_vec16 (void);

This code declares get_flt_vec16 to be a function returning a 16-byte vector with the base type float.

This example:

int foo [[gnu::vector_size (16)]];

causes the compiler to set the mode for foo to be 16 bytes, divided into int sized units. Assuming a 32-bit int, foo’s type is a vector of four units of four bytes each, and the corresponding mode of foo is V4SI.

This attribute is only applicable to integral and floating scalar base types, although arrays, pointers, and function return values are allowed in conjunction with this construct.

Aggregates with this attribute are invalid, even if they are of the same size as a corresponding scalar. For example, the declaration:

struct S { int a; };
struct S  __attribute__ ((vector_size (16))) foo;

is invalid even if the size of the structure is the same as the size of the int.

See Using Vector Instructions through Built-in Functions, for details of manipulating objects of vector types.

visibility ("visibility_type")

This attribute can be applied to functions, variables, and types.

It affects the linkage of the declaration to which it is attached. There are four supported visibility_type values: default, hidden, protected, or internal visibility.

[[gnu::visibility ("protected")]]
void f () { /* Do something. */; }

int i [[gnu::visibility ("hidden")]];

The possible values of visibility_type correspond to the visibility settings in the ELF gABI.

default

Default visibility is the normal case for the object file format. This value is available for the visibility attribute to override other options that may change the assumed visibility of entities.

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

Hidden visibility indicates that the entity declared has a new form of linkage, which we call “hidden linkage”. Two declarations of an object with hidden linkage refer to the same object if they are in the same shared object.

internal

Internal visibility is like hidden visibility, but with additional processor specific semantics. Unless otherwise specified by the psABI, GCC defines internal visibility to mean that a function is never called from another module. Compare this with hidden functions which, while they cannot be referenced directly by other modules, can be referenced indirectly via function pointers. By indicating that a function cannot be called from outside the module, GCC may for instance omit the load of a PIC register since it is known that the calling function loaded the correct value.

protected

Protected visibility is like default visibility except that it indicates that references within the defining module bind to the definition in that module. That is, the declared entity cannot be overridden by another module.

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.

In C++, attribute visibility can also be applied to class, struct, union and enum types. Unlike other type attributes, the attribute must appear between the initial keyword and the name of the type; it cannot appear after the body of the type.

Note that the type visibility is applied to vague linkage entities associated with the class (vtable, typeinfo node, etc.). In particular, if a class is thrown as an exception in one shared object and caught in another, the class must have default visibility. Otherwise the two shared objects are unable to use the same typeinfo node and exception handling will break.

warn_if_not_aligned (alignment)

This attribute applies to structure fields.

It specifies an alignment threshold, measured in bytes, for the field. If the structure field is aligned below the threshold, a warning is issued.

For example, the declaration:

struct foo
{
  int i1;
  int i2;
  unsigned long long x __attribute__ ((warn_if_not_aligned (16)));
};

causes the compiler to issue an warning on struct foo, like ‘warning: alignment 8 of 'struct foo' is less than 16’. The compiler also issues a warning, like ‘warning: 'x' offset 8 in 'struct foo' isn't aligned to 16’, when the structure field has the misaligned offset:

struct __attribute__ ((aligned (16))) foo
{
  int i1;
  int i2;
  unsigned long long x __attribute__ ((warn_if_not_aligned (16)));
};

This attribute can also be applied to a typedef, in which case it applies to all structure fields of that type.

For example, this code:

typedef unsigned long long __u64
  [[gnu::aligned (4), gnu::warn_if_not_aligned (8)]];

struct foo
{
  int i1;
  int i2;
  __u64 x;
};

has similar behavior to the first example above.

This warning can be disabled by -Wno-if-not-aligned.

warn_unused_result

This attribute applies to functions.

The 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.

[[gnu::warn_unused_result]] int fn (void);
int foo (void)
{
  if (fn () < 0) return -1;
  fn ();
  return 0;
}

results in a warning on line 5.

weak

This attribute applies to function and variable declarations.

The weak attribute causes a declaration of an external symbol 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. The overriding symbol must have the same type as the weak symbol. In addition, if it designates a variable it must also have the same size and alignment as the weak symbol. Weak symbols are supported for ELF targets, and also for a.out targets when using the GNU assembler and linker.

weakref
weakref ("target")

This attribute applies to function or variable declarations.

The weakref attribute marks the declaration of the entity as a weak reference. Without arguments, it should be accompanied by an alias attribute naming the target symbol. Alternatively, target may be given as an argument to weakref itself, naming the target definition of the alias. The target must have the same type as the declaration. In addition, if it designates a variable it must also have the same size and alignment as the declaration. In either form of the declaration weakref implicitly marks the declared symbol as weak. Without a target given as an argument to weakref or to alias, weakref is equivalent to weak (in that case the declaration may be extern).

/* Given the declaration: */
extern int y (void);

/* the following... */
static int x (void) __attribute__ ((weakref ("y")));

/* is equivalent to... */
static int x (void) __attribute__ ((weakref, alias ("y")));

/* or, alternatively, to... */
static int x (void) __attribute__ ((weakref));
static int x (void) __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 link with relocatable output (i.e. ld -r) on them.

A declaration to which weakref is attached and that is associated with a named target must be static.

zero_call_used_regs ("choice")

This attribute applies to functions.

The zero_call_used_regs attribute causes the compiler to zero a subset of all call-used registers5 at function return. This is used to increase program security by either mitigating Return-Oriented Programming (ROP) attacks or preventing information leakage through registers.

In order to satisfy users with different security needs and control the run-time overhead at the same time, the choice parameter provides a flexible way to choose the subset of the call-used registers to be zeroed. The four basic values of choice are:

  • skip’ doesn’t zero any call-used registers.
  • used’ only zeros call-used registers that are used in the function. A “used” register is one whose content has been set or referenced in the function.
  • all’ zeros all call-used registers.
  • leafy’ behaves like ‘used’ in a leaf function, and like ‘all’ in a nonleaf function. This makes for leaner zeroing in leaf functions, where the set of used registers is known, and that may be enough for some purposes of register zeroing.

In addition to these three basic choices, it is possible to modify ‘used’, ‘all’, and ‘leafy’ as follows:

  • Adding ‘-gpr’ restricts the zeroing to general-purpose registers.
  • Adding ‘-arg’ restricts the zeroing to registers that can sometimes be used to pass function arguments. This includes all argument registers defined by the platform’s calling conversion, regardless of whether the function uses those registers for function arguments or not.

The modifiers can be used individually or together. If they are used together, they must appear in the order above.

The full list of choices is therefore:

skip

doesn’t zero any call-used register.

used

only zeros call-used registers that are used in the function.

used-gpr

only zeros call-used general purpose registers that are used in the function.

used-arg

only zeros call-used registers that are used in the function and pass arguments.

used-gpr-arg

only zeros call-used general purpose registers that are used in the function and pass arguments.

all

zeros all call-used registers.

all-gpr

zeros all call-used general purpose registers.

all-arg

zeros all call-used registers that pass arguments.

all-gpr-arg

zeros all call-used general purpose registers that pass arguments.

leafy

Same as ‘used’ in a leaf function, and same as ‘all’ in a nonleaf function.

leafy-gpr

Same as ‘used-gpr’ in a leaf function, and same as ‘all-gpr’ in a nonleaf function.

leafy-arg

Same as ‘used-arg’ in a leaf function, and same as ‘all-arg’ in a nonleaf function.

leafy-gpr-arg

Same as ‘used-gpr-arg’ in a leaf function, and same as ‘all-gpr-arg’ in a nonleaf function.

Of this list, ‘used-arg’, ‘used-gpr-arg’, ‘all-arg’, ‘all-gpr-arg’, ‘leafy-arg’, and ‘leafy-gpr-arg’ are mainly used for ROP mitigation.

The default for the attribute is controlled by -fzero-call-used-regs.


Footnotes

(5)

A “call-used” register is a register whose contents can be changed by a function call; therefore, a caller cannot assume that the register has the same contents on return from the function as it had before calling the function. Such registers are also called “call-clobbered”, “caller-saved”, or “volatile”.