| c Copyright (C) 1988-2022 Free Software Foundation, Inc. |
| |
| @c This is part of the GCC manual. |
| @c For copying conditions, see the file gcc.texi. |
| |
| @node C Extensions |
| @chapter Extensions to the C Language Family |
| @cindex extensions, C language |
| @cindex C language extensions |
| |
| @opindex pedantic |
| GNU C provides several language features not found in ISO standard C@. |
| (The @option{-pedantic} option directs GCC to print a warning message if |
| any of these features is used.) To test for the availability of these |
| features in conditional compilation, check for a predefined macro |
| @code{__GNUC__}, which is always defined under GCC@. |
| |
| These extensions are available in C and Objective-C@. Most of them are |
| also available in C++. @xref{C++ Extensions,,Extensions to the |
| C++ Language}, for extensions that apply @emph{only} to C++. |
| |
| Some features that are in ISO C99 but not C90 or C++ are also, as |
| extensions, accepted by GCC in C90 mode and in C++. |
| |
| @menu |
| * Statement Exprs:: Putting statements and declarations inside expressions. |
| * Local Labels:: Labels local to a block. |
| * Labels as Values:: Getting pointers to labels, and computed gotos. |
| * Nested Functions:: Nested function in GNU C. |
| * Nonlocal Gotos:: Nonlocal gotos. |
| * Constructing Calls:: Dispatching a call to another function. |
| * Typeof:: @code{typeof}: referring to the type of an expression. |
| * Conditionals:: Omitting the middle operand of a @samp{?:} expression. |
| * __int128:: 128-bit integers---@code{__int128}. |
| * Long Long:: Double-word integers---@code{long long int}. |
| * Complex:: Data types for complex numbers. |
| * Floating Types:: Additional Floating Types. |
| * Half-Precision:: Half-Precision Floating Point. |
| * Decimal Float:: Decimal Floating Types. |
| * Hex Floats:: Hexadecimal floating-point constants. |
| * Fixed-Point:: Fixed-Point Types. |
| * Named Address Spaces::Named address spaces. |
| * Zero Length:: Zero-length arrays. |
| * Empty Structures:: Structures with no members. |
| * Variable Length:: Arrays whose length is computed at run time. |
| * Variadic Macros:: Macros with a variable number of arguments. |
| * Escaped Newlines:: Slightly looser rules for escaped newlines. |
| * Subscripting:: Any array can be subscripted, even if not an lvalue. |
| * Pointer Arith:: Arithmetic on @code{void}-pointers and function pointers. |
| * Variadic Pointer Args:: Pointer arguments to variadic functions. |
| * Pointers to Arrays:: Pointers to arrays with qualifiers work as expected. |
| * Initializers:: Non-constant initializers. |
| * Compound Literals:: Compound literals give structures, unions |
| or arrays as values. |
| * Designated Inits:: Labeling elements of initializers. |
| * Case Ranges:: `case 1 ... 9' and such. |
| * Cast to Union:: Casting to union type from any member of the union. |
| * Mixed Labels and Declarations:: Mixing declarations, labels and code. |
| * Function Attributes:: Declaring that functions have no side effects, |
| or that they can never return. |
| * Variable Attributes:: Specifying attributes of variables. |
| * Type Attributes:: Specifying attributes of types. |
| * Label Attributes:: Specifying attributes on labels. |
| * Enumerator Attributes:: Specifying attributes on enumerators. |
| * Statement Attributes:: Specifying attributes on statements. |
| * Attribute Syntax:: Formal syntax for attributes. |
| * Function Prototypes:: Prototype declarations and old-style definitions. |
| * C++ Comments:: C++ comments are recognized. |
| * Dollar Signs:: Dollar sign is allowed in identifiers. |
| * Character Escapes:: @samp{\e} stands for the character @key{ESC}. |
| * Alignment:: Determining the alignment of a function, type or variable. |
| * Inline:: Defining inline functions (as fast as macros). |
| * Volatiles:: What constitutes an access to a volatile object. |
| * Using Assembly Language with C:: Instructions and extensions for interfacing C with assembler. |
| * Alternate Keywords:: @code{__const__}, @code{__asm__}, etc., for header files. |
| * Incomplete Enums:: @code{enum foo;}, with details to follow. |
| * Function Names:: Printable strings which are the name of the current |
| function. |
| * Return Address:: Getting the return or frame address of a function. |
| * Vector Extensions:: Using vector instructions through built-in functions. |
| * Offsetof:: Special syntax for implementing @code{offsetof}. |
| * __sync Builtins:: Legacy built-in functions for atomic memory access. |
| * __atomic Builtins:: Atomic built-in functions with memory model. |
| * Integer Overflow Builtins:: Built-in functions to perform arithmetics and |
| arithmetic overflow checking. |
| * x86 specific memory model extensions for transactional memory:: x86 memory models. |
| * Object Size Checking:: Built-in functions for limited buffer overflow |
| checking. |
| * Other Builtins:: Other built-in functions. |
| * Target Builtins:: Built-in functions specific to particular targets. |
| * Target Format Checks:: Format checks specific to particular targets. |
| * Pragmas:: Pragmas accepted by GCC. |
| * Unnamed Fields:: Unnamed struct/union fields within structs/unions. |
| * Thread-Local:: Per-thread variables. |
| * Binary constants:: Binary constants using the @samp{0b} prefix. |
| @end menu |
| |
| @node Statement Exprs |
| @section Statements and Declarations in Expressions |
| @cindex statements inside expressions |
| @cindex declarations inside expressions |
| @cindex expressions containing statements |
| @cindex macros, statements in expressions |
| |
| @c the above section title wrapped and causes an underfull hbox.. i |
| @c changed it from "within" to "in". --mew 4feb93 |
| A compound statement enclosed in parentheses may appear as an expression |
| in GNU C@. This allows you to use loops, switches, and local variables |
| within an expression. |
| |
| Recall that a compound statement is a sequence of statements surrounded |
| by braces; in this construct, parentheses go around the braces. For |
| example: |
| |
| @smallexample |
| (@{ int y = foo (); int z; |
| if (y > 0) z = y; |
| else z = - y; |
| z; @}) |
| @end smallexample |
| |
| @noindent |
| is a valid (though slightly more complex than necessary) expression |
| for the absolute value of @code{foo ()}. |
| |
| The last thing in the compound statement should be an expression |
| followed by a semicolon; the value of this subexpression serves as the |
| value of the entire construct. (If you use some other kind of statement |
| last within the braces, the construct has type @code{void}, and thus |
| effectively no value.) |
| |
| This feature is especially useful in making macro definitions ``safe'' (so |
| that they evaluate each operand exactly once). For example, the |
| ``maximum'' function is commonly defined as a macro in standard C as |
| follows: |
| |
| @smallexample |
| #define max(a,b) ((a) > (b) ? (a) : (b)) |
| @end smallexample |
| |
| @noindent |
| @cindex side effects, macro argument |
| But this definition computes either @var{a} or @var{b} twice, with bad |
| results if the operand has side effects. In GNU C, if you know the |
| type of the operands (here taken as @code{int}), you can avoid this |
| problem by defining the macro as follows: |
| |
| @smallexample |
| #define maxint(a,b) \ |
| (@{int _a = (a), _b = (b); _a > _b ? _a : _b; @}) |
| @end smallexample |
| |
| Note that introducing variable declarations (as we do in @code{maxint}) can |
| cause variable shadowing, so while this example using the @code{max} macro |
| produces correct results: |
| @smallexample |
| int _a = 1, _b = 2, c; |
| c = max (_a, _b); |
| @end smallexample |
| @noindent |
| this example using maxint will not: |
| @smallexample |
| int _a = 1, _b = 2, c; |
| c = maxint (_a, _b); |
| @end smallexample |
| |
| This problem may for instance occur when we use this pattern recursively, like |
| so: |
| |
| @smallexample |
| #define maxint3(a, b, c) \ |
| (@{int _a = (a), _b = (b), _c = (c); maxint (maxint (_a, _b), _c); @}) |
| @end smallexample |
| |
| Embedded statements are not allowed in constant expressions, such as |
| the value of an enumeration constant, the width of a bit-field, or |
| the initial value of a static variable. |
| |
| If you don't know the type of the operand, you can still do this, but you |
| must use @code{typeof} or @code{__auto_type} (@pxref{Typeof}). |
| |
| In G++, the result value of a statement expression undergoes array and |
| function pointer decay, and is returned by value to the enclosing |
| expression. For instance, if @code{A} is a class, then |
| |
| @smallexample |
| A a; |
| |
| (@{a;@}).Foo () |
| @end smallexample |
| |
| @noindent |
| constructs a temporary @code{A} object to hold the result of the |
| statement expression, and that is used to invoke @code{Foo}. |
| Therefore the @code{this} pointer observed by @code{Foo} is not the |
| address of @code{a}. |
| |
| In a statement expression, any temporaries created within a statement |
| are destroyed at that statement's end. This makes statement |
| expressions inside macros slightly different from function calls. In |
| the latter case temporaries introduced during argument evaluation are |
| destroyed at the end of the statement that includes the function |
| call. In the statement expression case they are destroyed during |
| the statement expression. For instance, |
| |
| @smallexample |
| #define macro(a) (@{__typeof__(a) b = (a); b + 3; @}) |
| template<typename T> T function(T a) @{ T b = a; return b + 3; @} |
| |
| void foo () |
| @{ |
| macro (X ()); |
| function (X ()); |
| @} |
| @end smallexample |
| |
| @noindent |
| has different places where temporaries are destroyed. For the |
| @code{macro} case, the temporary @code{X} is destroyed just after |
| the initialization of @code{b}. In the @code{function} case that |
| temporary is destroyed when the function returns. |
| |
| These considerations mean that it is probably a bad idea to use |
| statement expressions of this form in header files that are designed to |
| work with C++. (Note that some versions of the GNU C Library contained |
| header files using statement expressions that lead to precisely this |
| bug.) |
| |
| Jumping into a statement expression with @code{goto} or using a |
| @code{switch} statement outside the statement expression with a |
| @code{case} or @code{default} label inside the statement expression is |
| not permitted. Jumping into a statement expression with a computed |
| @code{goto} (@pxref{Labels as Values}) has undefined behavior. |
| Jumping out of a statement expression is permitted, but if the |
| statement expression is part of a larger expression then it is |
| unspecified which other subexpressions of that expression have been |
| evaluated except where the language definition requires certain |
| subexpressions to be evaluated before or after the statement |
| expression. A @code{break} or @code{continue} statement inside of |
| a statement expression used in @code{while}, @code{do} or @code{for} |
| loop or @code{switch} statement condition |
| or @code{for} statement init or increment expressions jumps to an |
| outer loop or @code{switch} statement if any (otherwise it is an error), |
| rather than to the loop or @code{switch} statement in whose condition |
| or init or increment expression it appears. |
| In any case, as with a function call, the evaluation of a |
| statement expression is not interleaved with the evaluation of other |
| parts of the containing expression. For example, |
| |
| @smallexample |
| foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz(); |
| @end smallexample |
| |
| @noindent |
| calls @code{foo} and @code{bar1} and does not call @code{baz} but |
| may or may not call @code{bar2}. If @code{bar2} is called, it is |
| called after @code{foo} and before @code{bar1}. |
| |
| @node Local Labels |
| @section Locally Declared Labels |
| @cindex local labels |
| @cindex macros, local labels |
| |
| GCC allows you to declare @dfn{local labels} in any nested block |
| scope. A local label is just like an ordinary label, but you can |
| only reference it (with a @code{goto} statement, or by taking its |
| address) within the block in which it is declared. |
| |
| A local label declaration looks like this: |
| |
| @smallexample |
| __label__ @var{label}; |
| @end smallexample |
| |
| @noindent |
| or |
| |
| @smallexample |
| __label__ @var{label1}, @var{label2}, /* @r{@dots{}} */; |
| @end smallexample |
| |
| Local label declarations must come at the beginning of the block, |
| before any ordinary declarations or statements. |
| |
| The label declaration defines the label @emph{name}, but does not define |
| the label itself. You must do this in the usual way, with |
| @code{@var{label}:}, within the statements of the statement expression. |
| |
| The local label feature is useful for complex macros. If a macro |
| contains nested loops, a @code{goto} can be useful for breaking out of |
| them. However, an ordinary label whose scope is the whole function |
| cannot be used: if the macro can be expanded several times in one |
| function, the label is multiply defined in that function. A |
| local label avoids this problem. For example: |
| |
| @smallexample |
| #define SEARCH(value, array, target) \ |
| do @{ \ |
| __label__ found; \ |
| typeof (target) _SEARCH_target = (target); \ |
| typeof (*(array)) *_SEARCH_array = (array); \ |
| int i, j; \ |
| int value; \ |
| for (i = 0; i < max; i++) \ |
| for (j = 0; j < max; j++) \ |
| if (_SEARCH_array[i][j] == _SEARCH_target) \ |
| @{ (value) = i; goto found; @} \ |
| (value) = -1; \ |
| found:; \ |
| @} while (0) |
| @end smallexample |
| |
| This could also be written using a statement expression: |
| |
| @smallexample |
| #define SEARCH(array, target) \ |
| (@{ \ |
| __label__ found; \ |
| typeof (target) _SEARCH_target = (target); \ |
| typeof (*(array)) *_SEARCH_array = (array); \ |
| int i, j; \ |
| int value; \ |
| for (i = 0; i < max; i++) \ |
| for (j = 0; j < max; j++) \ |
| if (_SEARCH_array[i][j] == _SEARCH_target) \ |
| @{ value = i; goto found; @} \ |
| value = -1; \ |
| found: \ |
| value; \ |
| @}) |
| @end smallexample |
| |
| Local label declarations also make the labels they declare visible to |
| nested functions, if there are any. @xref{Nested Functions}, for details. |
| |
| @node Labels as Values |
| @section Labels as Values |
| @cindex labels as values |
| @cindex computed gotos |
| @cindex goto with computed label |
| @cindex address of a label |
| |
| You can get the address of a label defined in the current function |
| (or a containing function) with the unary operator @samp{&&}. The |
| value has type @code{void *}. This value is a constant and can be used |
| wherever a constant of that type is valid. For example: |
| |
| @smallexample |
| void *ptr; |
| /* @r{@dots{}} */ |
| ptr = &&foo; |
| @end smallexample |
| |
| To use these values, you need to be able to jump to one. This is done |
| with the computed goto statement@footnote{The analogous feature in |
| Fortran is called an assigned goto, but that name seems inappropriate in |
| C, where one can do more than simply store label addresses in label |
| variables.}, @code{goto *@var{exp};}. For example, |
| |
| @smallexample |
| goto *ptr; |
| @end smallexample |
| |
| @noindent |
| Any expression of type @code{void *} is allowed. |
| |
| One way of using these constants is in initializing a static array that |
| serves as a jump table: |
| |
| @smallexample |
| static void *array[] = @{ &&foo, &&bar, &&hack @}; |
| @end smallexample |
| |
| @noindent |
| Then you can select a label with indexing, like this: |
| |
| @smallexample |
| goto *array[i]; |
| @end smallexample |
| |
| @noindent |
| Note that this does not check whether the subscript is in bounds---array |
| indexing in C never does that. |
| |
| Such an array of label values serves a purpose much like that of the |
| @code{switch} statement. The @code{switch} statement is cleaner, so |
| use that rather than an array unless the problem does not fit a |
| @code{switch} statement very well. |
| |
| Another use of label values is in an interpreter for threaded code. |
| The labels within the interpreter function can be stored in the |
| threaded code for super-fast dispatching. |
| |
| You may not use this mechanism to jump to code in a different function. |
| If you do that, totally unpredictable things happen. The best way to |
| avoid this is to store the label address only in automatic variables and |
| never pass it as an argument. |
| |
| An alternate way to write the above example is |
| |
| @smallexample |
| static const int array[] = @{ &&foo - &&foo, &&bar - &&foo, |
| &&hack - &&foo @}; |
| goto *(&&foo + array[i]); |
| @end smallexample |
| |
| @noindent |
| This is more friendly to code living in shared libraries, as it reduces |
| the number of dynamic relocations that are needed, and by consequence, |
| allows the data to be read-only. |
| This alternative with label differences is not supported for the AVR target, |
| please use the first approach for AVR programs. |
| |
| The @code{&&foo} expressions for the same label might have different |
| values if the containing function is inlined or cloned. If a program |
| relies on them being always the same, |
| @code{__attribute__((__noinline__,__noclone__))} should be used to |
| prevent inlining and cloning. If @code{&&foo} is used in a static |
| variable initializer, inlining and cloning is forbidden. |
| |
| @node Nested Functions |
| @section Nested Functions |
| @cindex nested functions |
| @cindex downward funargs |
| @cindex thunks |
| |
| A @dfn{nested function} is a function defined inside another function. |
| Nested functions are supported as an extension in GNU C, but are not |
| supported by GNU C++. |
| |
| The nested function's name is local to the block where it is defined. |
| For example, here we define a nested function named @code{square}, and |
| call it twice: |
| |
| @smallexample |
| @group |
| foo (double a, double b) |
| @{ |
| double square (double z) @{ return z * z; @} |
| |
| return square (a) + square (b); |
| @} |
| @end group |
| @end smallexample |
| |
| The nested function can access all the variables of the containing |
| function that are visible at the point of its definition. This is |
| called @dfn{lexical scoping}. For example, here we show a nested |
| function which uses an inherited variable named @code{offset}: |
| |
| @smallexample |
| @group |
| bar (int *array, int offset, int size) |
| @{ |
| int access (int *array, int index) |
| @{ return array[index + offset]; @} |
| int i; |
| /* @r{@dots{}} */ |
| for (i = 0; i < size; i++) |
| /* @r{@dots{}} */ access (array, i) /* @r{@dots{}} */ |
| @} |
| @end group |
| @end smallexample |
| |
| Nested function definitions are permitted within functions in the places |
| where variable definitions are allowed; that is, in any block, mixed |
| with the other declarations and statements in the block. |
| |
| It is possible to call the nested function from outside the scope of its |
| name by storing its address or passing the address to another function: |
| |
| @smallexample |
| hack (int *array, int size) |
| @{ |
| void store (int index, int value) |
| @{ array[index] = value; @} |
| |
| intermediate (store, size); |
| @} |
| @end smallexample |
| |
| Here, the function @code{intermediate} receives the address of |
| @code{store} as an argument. If @code{intermediate} calls @code{store}, |
| the arguments given to @code{store} are used to store into @code{array}. |
| But this technique works only so long as the containing function |
| (@code{hack}, in this example) does not exit. |
| |
| If you try to call the nested function through its address after the |
| containing function exits, all hell breaks loose. If you try |
| to call it after a containing scope level exits, and if it refers |
| to some of the variables that are no longer in scope, you may be lucky, |
| but it's not wise to take the risk. If, however, the nested function |
| does not refer to anything that has gone out of scope, you should be |
| safe. |
| |
| GCC implements taking the address of a nested function using a technique |
| called @dfn{trampolines}. This technique was described in |
| @cite{Lexical Closures for C++} (Thomas M. Breuel, USENIX |
| C++ Conference Proceedings, October 17-21, 1988). |
| |
| A nested function can jump to a label inherited from a containing |
| function, provided the label is explicitly declared in the containing |
| function (@pxref{Local Labels}). Such a jump returns instantly to the |
| containing function, exiting the nested function that did the |
| @code{goto} and any intermediate functions as well. Here is an example: |
| |
| @smallexample |
| @group |
| bar (int *array, int offset, int size) |
| @{ |
| __label__ failure; |
| int access (int *array, int index) |
| @{ |
| if (index > size) |
| goto failure; |
| return array[index + offset]; |
| @} |
| int i; |
| /* @r{@dots{}} */ |
| for (i = 0; i < size; i++) |
| /* @r{@dots{}} */ access (array, i) /* @r{@dots{}} */ |
| /* @r{@dots{}} */ |
| return 0; |
| |
| /* @r{Control comes here from @code{access} |
| if it detects an error.} */ |
| failure: |
| return -1; |
| @} |
| @end group |
| @end smallexample |
| |
| A nested function always has no linkage. Declaring one with |
| @code{extern} or @code{static} is erroneous. If you need to declare the nested function |
| before its definition, use @code{auto} (which is otherwise meaningless |
| for function declarations). |
| |
| @smallexample |
| bar (int *array, int offset, int size) |
| @{ |
| __label__ failure; |
| auto int access (int *, int); |
| /* @r{@dots{}} */ |
| int access (int *array, int index) |
| @{ |
| if (index > size) |
| goto failure; |
| return array[index + offset]; |
| @} |
| /* @r{@dots{}} */ |
| @} |
| @end smallexample |
| |
| @node Nonlocal Gotos |
| @section Nonlocal Gotos |
| @cindex nonlocal gotos |
| |
| GCC provides the built-in functions @code{__builtin_setjmp} and |
| @code{__builtin_longjmp} which are similar to, but not interchangeable |
| with, the C library functions @code{setjmp} and @code{longjmp}. |
| The built-in versions are used internally by GCC's libraries |
| to implement exception handling on some targets. You should use the |
| standard C library functions declared in @code{<setjmp.h>} in user code |
| instead of the builtins. |
| |
| The built-in versions of these functions use GCC's normal |
| mechanisms to save and restore registers using the stack on function |
| entry and exit. The jump buffer argument @var{buf} holds only the |
| information needed to restore the stack frame, rather than the entire |
| set of saved register values. |
| |
| An important caveat is that GCC arranges to save and restore only |
| those registers known to the specific architecture variant being |
| compiled for. This can make @code{__builtin_setjmp} and |
| @code{__builtin_longjmp} more efficient than their library |
| counterparts in some cases, but it can also cause incorrect and |
| mysterious behavior when mixing with code that uses the full register |
| set. |
| |
| You should declare the jump buffer argument @var{buf} to the |
| built-in functions as: |
| |
| @smallexample |
| #include <stdint.h> |
| intptr_t @var{buf}[5]; |
| @end smallexample |
| |
| @deftypefn {Built-in Function} {int} __builtin_setjmp (intptr_t *@var{buf}) |
| This function saves the current stack context in @var{buf}. |
| @code{__builtin_setjmp} returns 0 when returning directly, |
| and 1 when returning from @code{__builtin_longjmp} using the same |
| @var{buf}. |
| @end deftypefn |
| |
| @deftypefn {Built-in Function} {void} __builtin_longjmp (intptr_t *@var{buf}, int @var{val}) |
| This function restores the stack context in @var{buf}, |
| saved by a previous call to @code{__builtin_setjmp}. After |
| @code{__builtin_longjmp} is finished, the program resumes execution as |
| if the matching @code{__builtin_setjmp} returns the value @var{val}, |
| which must be 1. |
| |
| Because @code{__builtin_longjmp} depends on the function return |
| mechanism to restore the stack context, it cannot be called |
| from the same function calling @code{__builtin_setjmp} to |
| initialize @var{buf}. It can only be called from a function called |
| (directly or indirectly) from the function calling @code{__builtin_setjmp}. |
| @end deftypefn |
| |
| @node Constructing Calls |
| @section Constructing Function Calls |
| @cindex constructing calls |
| @cindex forwarding calls |
| |
| Using the built-in functions described below, you can record |
| the arguments a function received, and call another function |
| with the same arguments, without knowing the number or types |
| of the arguments. |
| |
| You can also record the return value of that function call, |
| and later return that value, without knowing what data type |
| the function tried to return (as long as your caller expects |
| that data type). |
| |
| However, these built-in functions may interact badly with some |
| sophisticated features or other extensions of the language. It |
| is, therefore, not recommended to use them outside very simple |
| functions acting as mere forwarders for their arguments. |
| |
| @deftypefn {Built-in Function} {void *} __builtin_apply_args () |
| This built-in function returns a pointer to data |
| describing how to perform a call with the same arguments as are passed |
| to the current function. |
| |
| The function saves the arg pointer register, structure value address, |
| and all registers that might be used to pass arguments to a function |
| into a block of memory allocated on the stack. Then it returns the |
| address of that block. |
| @end deftypefn |
| |
| @deftypefn {Built-in Function} {void *} __builtin_apply (void (*@var{function})(), void *@var{arguments}, size_t @var{size}) |
| This built-in function invokes @var{function} |
| with a copy of the parameters described by @var{arguments} |
| and @var{size}. |
| |
| The value of @var{arguments} should be the value returned by |
| @code{__builtin_apply_args}. The argument @var{size} specifies the size |
| of the stack argument data, in bytes. |
| |
| This function returns a pointer to data describing |
| how to return whatever value is returned by @var{function}. The data |
| is saved in a block of memory allocated on the stack. |
| |
| It is not always simple to compute the proper value for @var{size}. The |
| value is used by @code{__builtin_apply} to compute the amount of data |
| that should be pushed on the stack and copied from the incoming argument |
| area. |
| @end deftypefn |
| |
| @deftypefn {Built-in Function} {void} __builtin_return (void *@var{result}) |
| This built-in function returns the value described by @var{result} from |
| the containing function. You should specify, for @var{result}, a value |
| returned by @code{__builtin_apply}. |
| @end deftypefn |
| |
| @deftypefn {Built-in Function} {} __builtin_va_arg_pack () |
| This built-in function represents all anonymous arguments of an inline |
| function. It can be used only in inline functions that are always |
| inlined, never compiled as a separate function, such as those using |
| @code{__attribute__ ((__always_inline__))} or |
| @code{__attribute__ ((__gnu_inline__))} extern inline functions. |
| It must be only passed as last argument to some other function |
| with variable arguments. This is useful for writing small wrapper |
| inlines for variable argument functions, when using preprocessor |
| macros is undesirable. For example: |
| @smallexample |
| extern int myprintf (FILE *f, const char *format, ...); |
| extern inline __attribute__ ((__gnu_inline__)) int |
| myprintf (FILE *f, const char *format, ...) |
| @{ |
| int r = fprintf (f, "myprintf: "); |
| if (r < 0) |
| return r; |
| int s = fprintf (f, format, __builtin_va_arg_pack ()); |
| if (s < 0) |
| return s; |
| return r + s; |
| @} |
| @end smallexample |
| @end deftypefn |
| |
| @deftypefn {Built-in Function} {size_t} __builtin_va_arg_pack_len () |
| This built-in function returns the number of anonymous arguments of |
| an inline function. It can be used only in inline functions that |
| are always inlined, never compiled as a separate function, such |
| as those using @code{__attribute__ ((__always_inline__))} or |
| @code{__attribute__ ((__gnu_inline__))} extern inline functions. |
| For example following does link- or run-time checking of open |
| arguments for optimized code: |
| @smallexample |
| #ifdef __OPTIMIZE__ |
| extern inline __attribute__((__gnu_inline__)) int |
| myopen (const char *path, int oflag, ...) |
| @{ |
| if (__builtin_va_arg_pack_len () > 1) |
| warn_open_too_many_arguments (); |
| |
| if (__builtin_constant_p (oflag)) |
| @{ |
| if ((oflag & O_CREAT) != 0 && __builtin_va_arg_pack_len () < 1) |
| @{ |
| warn_open_missing_mode (); |
| return __open_2 (path, oflag); |
| @} |
| return open (path, oflag, __builtin_va_arg_pack ()); |
| @} |
| |
| if (__builtin_va_arg_pack_len () < 1) |
| return __open_2 (path, oflag); |
| |
| return open (path, oflag, __builtin_va_arg_pack ()); |
| @} |
| #endif |
| @end smallexample |
| @end deftypefn |
| |
| @node Typeof |
| @section Referring to a Type with @code{typeof} |
| @findex typeof |
| @findex sizeof |
| @cindex macros, types of arguments |
| |
| Another way to refer to the type of an expression is with @code{typeof}. |
| The syntax of using of this keyword looks like @code{sizeof}, but the |
| construct acts semantically like a type name defined with @code{typedef}. |
| |
| There are two ways of writing the argument to @code{typeof}: with an |
| expression or with a type. Here is an example with an expression: |
| |
| @smallexample |
| typeof (x[0](1)) |
| @end smallexample |
| |
| @noindent |
| This assumes that @code{x} is an array of pointers to functions; |
| the type described is that of the values of the functions. |
| |
| Here is an example with a typename as the argument: |
| |
| @smallexample |
| typeof (int *) |
| @end smallexample |
| |
| @noindent |
| Here the type described is that of pointers to @code{int}. |
| |
| If you are writing a header file that must work when included in ISO C |
| programs, write @code{__typeof__} instead of @code{typeof}. |
| @xref{Alternate Keywords}. |
| |
| A @code{typeof} construct can be used anywhere a typedef name can be |
| used. For example, you can use it in a declaration, in a cast, or inside |
| of @code{sizeof} or @code{typeof}. |
| |
| The operand of @code{typeof} is evaluated for its side effects if and |
| only if it is an expression of variably modified type or the name of |
| such a type. |
| |
| @code{typeof} is often useful in conjunction with |
| statement expressions (@pxref{Statement Exprs}). |
| Here is how the two together can |
| be used to define a safe ``maximum'' macro which operates on any |
| arithmetic type and evaluates each of its arguments exactly once: |
| |
| @smallexample |
| #define max(a,b) \ |
| (@{ typeof (a) _a = (a); \ |
| typeof (b) _b = (b); \ |
| _a > _b ? _a : _b; @}) |
| @end smallexample |
| |
| @cindex underscores in variables in macros |
| @cindex @samp{_} in variables in macros |
| @cindex local variables in macros |
| @cindex variables, local, in macros |
| @cindex macros, local variables in |
| |
| The reason for using names that start with underscores for the local |
| variables is to avoid conflicts with variable names that occur within the |
| expressions that are substituted for @code{a} and @code{b}. Eventually we |
| hope to design a new form of declaration syntax that allows you to declare |
| variables whose scopes start only after their initializers; this will be a |
| more reliable way to prevent such conflicts. |
| |
| @noindent |
| Some more examples of the use of @code{typeof}: |
| |
| @itemize @bullet |
| @item |
| This declares @code{y} with the type of what @code{x} points to. |
| |
| @smallexample |
| typeof (*x) y; |
| @end smallexample |
| |
| @item |
| This declares @code{y} as an array of such values. |
| |
| @smallexample |
| typeof (*x) y[4]; |
| @end smallexample |
| |
| @item |
| This declares @code{y} as an array of pointers to characters: |
| |
| @smallexample |
| typeof (typeof (char *)[4]) y; |
| @end smallexample |
| |
| @noindent |
| It is equivalent to the following traditional C declaration: |
| |
| @smallexample |
| char *y[4]; |
| @end smallexample |
| |
| To see the meaning of the declaration using @code{typeof}, and why it |
| might be a useful way to write, rewrite it with these macros: |
| |
| @smallexample |
| #define pointer(T) typeof(T *) |
| #define array(T, N) typeof(T [N]) |
| @end smallexample |
| |
| @noindent |
| Now the declaration can be rewritten this way: |
| |
| @smallexample |
| array (pointer (char), 4) y; |
| @end smallexample |
| |
| @noindent |
| Thus, @code{array (pointer (char), 4)} is the type of arrays of 4 |
| pointers to @code{char}. |
| @end itemize |
| |
| In GNU C, but not GNU C++, you may also declare the type of a variable |
| as @code{__auto_type}. In that case, the declaration must declare |
| only one variable, whose declarator must just be an identifier, the |
| declaration must be initialized, and the type of the variable is |
| determined by the initializer; the name of the variable is not in |
| scope until after the initializer. (In C++, you should use C++11 |
| @code{auto} for this purpose.) Using @code{__auto_type}, the |
| ``maximum'' macro above could be written as: |
| |
| @smallexample |
| #define max(a,b) \ |
| (@{ __auto_type _a = (a); \ |
| __auto_type _b = (b); \ |
| _a > _b ? _a : _b; @}) |
| @end smallexample |
| |
| Using @code{__auto_type} instead of @code{typeof} has two advantages: |
| |
| @itemize @bullet |
| @item Each argument to the macro appears only once in the expansion of |
| the macro. This prevents the size of the macro expansion growing |
| exponentially when calls to such macros are nested inside arguments of |
| such macros. |
| |
| @item If the argument to the macro has variably modified type, it is |
| evaluated only once when using @code{__auto_type}, but twice if |
| @code{typeof} is used. |
| @end itemize |
| |
| @node Conditionals |
| @section Conditionals with Omitted Operands |
| @cindex conditional expressions, extensions |
| @cindex omitted middle-operands |
| @cindex middle-operands, omitted |
| @cindex extensions, @code{?:} |
| @cindex @code{?:} extensions |
| |
| The middle operand in a conditional expression may be omitted. Then |
| if the first operand is nonzero, its value is the value of the conditional |
| expression. |
| |
| Therefore, the expression |
| |
| @smallexample |
| x ? : y |
| @end smallexample |
| |
| @noindent |
| has the value of @code{x} if that is nonzero; otherwise, the value of |
| @code{y}. |
| |
| This example is perfectly equivalent to |
| |
| @smallexample |
| x ? x : y |
| @end smallexample |
| |
| @cindex side effect in @code{?:} |
| @cindex @code{?:} side effect |
| @noindent |
| In this simple case, the ability to omit the middle operand is not |
| especially useful. When it becomes useful is when the first operand does, |
| or may (if it is a macro argument), contain a side effect. Then repeating |
| the operand in the middle would perform the side effect twice. Omitting |
| the middle operand uses the value already computed without the undesirable |
| effects of recomputing it. |
| |
| @node __int128 |
| @section 128-bit Integers |
| @cindex @code{__int128} data types |
| |
| As an extension the integer scalar type @code{__int128} is supported for |
| targets which have an integer mode wide enough to hold 128 bits. |
| Simply write @code{__int128} for a signed 128-bit integer, or |
| @code{unsigned __int128} for an unsigned 128-bit integer. There is no |
| support in GCC for expressing an integer constant of type @code{__int128} |
| for targets with @code{long long} integer less than 128 bits wide. |
| |
| @node Long Long |
| @section Double-Word Integers |
| @cindex @code{long long} data types |
| @cindex double-word arithmetic |
| @cindex multiprecision arithmetic |
| @cindex @code{LL} integer suffix |
| @cindex @code{ULL} integer suffix |
| |
| ISO C99 and ISO C++11 support data types for integers that are at least |
| 64 bits wide, and as an extension GCC supports them in C90 and C++98 modes. |
| Simply write @code{long long int} for a signed integer, or |
| @code{unsigned long long int} for an unsigned integer. To make an |
| integer constant of type @code{long long int}, add the suffix @samp{LL} |
| to the integer. To make an integer constant of type @code{unsigned long |
| long int}, add the suffix @samp{ULL} to the integer. |
| |
| You can use these types in arithmetic like any other integer types. |
| Addition, subtraction, and bitwise boolean operations on these types |
| are open-coded on all types of machines. Multiplication is open-coded |
| if the machine supports a fullword-to-doubleword widening multiply |
| instruction. Division and shifts are open-coded only on machines that |
| provide special support. The operations that are not open-coded use |
| special library routines that come with GCC@. |
| |
| There may be pitfalls when you use @code{long long} types for function |
| arguments without function prototypes. If a function |
| expects type @code{int} for its argument, and you pass a value of type |
| @code{long long int}, confusion results because the caller and the |
| subroutine disagree about the number of bytes for the argument. |
| Likewise, if the function expects @code{long long int} and you pass |
| @code{int}. The best way to avoid such problems is to use prototypes. |
| |
| @node Complex |
| @section Complex Numbers |
| @cindex complex numbers |
| @cindex @code{_Complex} keyword |
| @cindex @code{__complex__} keyword |
| |
| ISO C99 supports complex floating data types, and as an extension GCC |
| supports them in C90 mode and in C++. GCC also supports complex integer data |
| types which are not part of ISO C99. You can declare complex types |
| using the keyword @code{_Complex}. As an extension, the older GNU |
| keyword @code{__complex__} is also supported. |
| |
| For example, @samp{_Complex double x;} declares @code{x} as a |
| variable whose real part and imaginary part are both of type |
| @code{double}. @samp{_Complex short int y;} declares @code{y} to |
| have real and imaginary parts of type @code{short int}; this is not |
| likely to be useful, but it shows that the set of complex types is |
| complete. |
| |
| To write a constant with a complex data type, use the suffix @samp{i} or |
| @samp{j} (either one; they are equivalent). For example, @code{2.5fi} |
| has type @code{_Complex float} and @code{3i} has type |
| @code{_Complex int}. Such a constant always has a pure imaginary |
| value, but you can form any complex value you like by adding one to a |
| real constant. This is a GNU extension; if you have an ISO C99 |
| conforming C library (such as the GNU C Library), and want to construct complex |
| constants of floating type, you should include @code{<complex.h>} and |
| use the macros @code{I} or @code{_Complex_I} instead. |
| |
| The ISO C++14 library also defines the @samp{i} suffix, so C++14 code |
| that includes the @samp{<complex>} header cannot use @samp{i} for the |
| GNU extension. The @samp{j} suffix still has the GNU meaning. |
| |
| GCC can handle both implicit and explicit casts between the @code{_Complex} |
| types and other @code{_Complex} types as casting both the real and imaginary |
| parts to the scalar type. |
| GCC can handle implicit and explicit casts from a scalar type to a @code{_Complex} |
| type and where the imaginary part will be considered zero. |
| The C front-end can handle implicit and explicit casts from a @code{_Complex} type |
| to a scalar type where the imaginary part will be ignored. In C++ code, this cast |
| is considered illformed and G++ will error out. |
| |
| GCC provides a built-in function @code{__builtin_complex} will can be used to |
| construct a complex value. |
| |
| @cindex @code{__real__} keyword |
| @cindex @code{__imag__} keyword |
| |
| GCC has a few extensions which can be used to extract the real |
| and the imaginary part of the complex-valued expression. Note |
| these expressions are lvalues if the @var{exp} is an lvalue. |
| These expressions operands have the type of a complex type |
| which might get prompoted to a complex type from a scalar type. |
| E.g. @code{__real__ (int)@var{x}} is the same as casting to |
| @code{_Complex int} before @code{__real__} is done. |
| |
| @multitable @columnfractions .4 .6 |
| @headitem Expression @tab Description |
| @item @code{__real__ @var{exp}} |
| @tab Extract the real part of @var{exp}. |
| @item @code{__imag__ @var{exp}} |
| @tab Extract the imaginary part of @var{exp}. |
| @end multitable |
| |
| For values of floating point, you should use the ISO C99 |
| functions, declared in @code{<complex.h>} and also provided as |
| built-in functions by GCC@. |
| |
| @multitable @columnfractions .4 .2 .2 .2 |
| @headitem Expression @tab float @tab double @tab long double |
| @item @code{__real__ @var{exp}} |
| @tab @code{crealf} @tab @code{creal} @tab @code{creall} |
| @item @code{__imag__ @var{exp}} |
| @tab @code{cimagf} @tab @code{cimag} @tab @code{cimagl} |
| @end multitable |
| |
| @cindex complex conjugation |
| The operator @samp{~} performs complex conjugation when used on a value |
| with a complex type. This is a GNU extension; for values of |
| floating type, you should use the ISO C99 functions @code{conjf}, |
| @code{conj} and @code{conjl}, declared in @code{<complex.h>} and also |
| provided as built-in functions by GCC@. Note unlike the @code{__real__} |
| and @code{__imag__} operators, this operator will not do an implicit cast |
| to the complex type because the @samp{~} is already a normal operator. |
| |
| GCC can allocate complex automatic variables in a noncontiguous |
| fashion; it's even possible for the real part to be in a register while |
| the imaginary part is on the stack (or vice versa). Only the DWARF |
| debug info format can represent this, so use of DWARF is recommended. |
| If you are using the stabs debug info format, GCC describes a noncontiguous |
| complex variable as if it were two separate variables of noncomplex type. |
| If the variable's actual name is @code{foo}, the two fictitious |
| variables are named @code{foo$real} and @code{foo$imag}. You can |
| examine and set these two fictitious variables with your debugger. |
| |
| @deftypefn {Built-in Function} @var{type} __builtin_complex (@var{real}, @var{imag}) |
| |
| The built-in function @code{__builtin_complex} is provided for use in |
| implementing the ISO C11 macros @code{CMPLXF}, @code{CMPLX} and |
| @code{CMPLXL}. @var{real} and @var{imag} must have the same type, a |
| real binary floating-point type, and the result has the corresponding |
| complex type with real and imaginary parts @var{real} and @var{imag}. |
| Unlike @samp{@var{real} + I * @var{imag}}, this works even when |
| infinities, NaNs and negative zeros are involved. |
| |
| @end deftypefn |
| |
| @node Floating Types |
| @section Additional Floating Types |
| @cindex additional floating types |
| @cindex @code{_Float@var{n}} data types |
| @cindex @code{_Float@var{n}x} data types |
| @cindex @code{__float80} data type |
| @cindex @code{__float128} data type |
| @cindex @code{__ibm128} data type |
| @cindex @code{w} floating point suffix |
| @cindex @code{q} floating point suffix |
| @cindex @code{W} floating point suffix |
| @cindex @code{Q} floating point suffix |
| |
| ISO/IEC TS 18661-3:2015 defines C support for additional floating |
| types @code{_Float@var{n}} and @code{_Float@var{n}x}, and GCC supports |
| these type names; the set of types supported depends on the target |
| architecture. These types are not supported when compiling C++. |
| Constants with these types use suffixes @code{f@var{n}} or |
| @code{F@var{n}} and @code{f@var{n}x} or @code{F@var{n}x}. These type |
| names can be used together with @code{_Complex} to declare complex |
| types. |
| |
| As an extension, GNU C and GNU C++ support additional floating |
| types, which are not supported by all targets. |
| @itemize @bullet |
| @item @code{__float128} is available on i386, x86_64, IA-64, and |
| hppa HP-UX, as well as on PowerPC GNU/Linux targets that enable |
| the vector scalar (VSX) instruction set. @code{__float128} supports |
| the 128-bit floating type. On i386, x86_64, PowerPC, and IA-64 |
| other than HP-UX, @code{__float128} is an alias for @code{_Float128}. |
| On hppa and IA-64 HP-UX, @code{__float128} is an alias for @code{long |
| double}. |
| |
| @item @code{__float80} is available on the i386, x86_64, and IA-64 |
| targets, and supports the 80-bit (@code{XFmode}) floating type. It is |
| an alias for the type name @code{_Float64x} on these targets. |
| |
| @item @code{__ibm128} is available on PowerPC targets, and provides |
| access to the IBM extended double format which is the current format |
| used for @code{long double}. When @code{long double} transitions to |
| @code{__float128} on PowerPC in the future, @code{__ibm128} will remain |
| for use in conversions between the two types. |
| @end itemize |
| |
| Support for these additional types includes the arithmetic operators: |
| add, subtract, multiply, divide; unary arithmetic operators; |
| relational operators; equality operators; and conversions to and from |
| integer and other floating types. Use a suffix @samp{w} or @samp{W} |
| in a literal constant of type @code{__float80} or type |
| @code{__ibm128}. Use a suffix @samp{q} or @samp{Q} for @code{_float128}. |
| |
| In order to use @code{_Float128}, @code{__float128}, and @code{__ibm128} |
| on PowerPC Linux systems, you must use the @option{-mfloat128} option. It is |
| expected in future versions of GCC that @code{_Float128} and @code{__float128} |
| will be enabled automatically. |
| |
| The @code{_Float128} type is supported on all systems where |
| @code{__float128} is supported or where @code{long double} has the |
| IEEE binary128 format. The @code{_Float64x} type is supported on all |
| systems where @code{__float128} is supported. The @code{_Float32} |
| type is supported on all systems supporting IEEE binary32; the |
| @code{_Float64} and @code{_Float32x} types are supported on all systems |
| supporting IEEE binary64. The @code{_Float16} type is supported on AArch64 |
| systems by default, on ARM systems when the IEEE format for 16-bit |
| floating-point types is selected with @option{-mfp16-format=ieee} and, |
| for both C and C++, on x86 systems with SSE2 enabled. GCC does not currently |
| support @code{_Float128x} on any systems. |
| |
| On the i386, x86_64, IA-64, and HP-UX targets, you can declare complex |
| types using the corresponding internal complex type, @code{XCmode} for |
| @code{__float80} type and @code{TCmode} for @code{__float128} type: |
| |
| @smallexample |
| typedef _Complex float __attribute__((mode(TC))) _Complex128; |
| typedef _Complex float __attribute__((mode(XC))) _Complex80; |
| @end smallexample |
| |
| On the PowerPC Linux VSX targets, you can declare complex types using |
| the corresponding internal complex type, @code{KCmode} for |
| @code{__float128} type and @code{ICmode} for @code{__ibm128} type: |
| |
| @smallexample |
| typedef _Complex float __attribute__((mode(KC))) _Complex_float128; |
| typedef _Complex float __attribute__((mode(IC))) _Complex_ibm128; |
| @end smallexample |
| |
| @node Half-Precision |
| @section Half-Precision Floating Point |
| @cindex half-precision floating point |
| @cindex @code{__fp16} data type |
| @cindex @code{__Float16} data type |
| |
| On ARM and AArch64 targets, GCC supports half-precision (16-bit) floating |
| point via the @code{__fp16} type defined in the ARM C Language Extensions. |
| On ARM systems, you must enable this type explicitly with the |
| @option{-mfp16-format} command-line option in order to use it. |
| On x86 targets with SSE2 enabled, GCC supports half-precision (16-bit) |
| floating point via the @code{_Float16} type. For C++, x86 provides a builtin |
| type named @code{_Float16} which contains same data format as C. |
| |
| ARM targets support two incompatible representations for half-precision |
| floating-point values. You must choose one of the representations and |
| use it consistently in your program. |
| |
| Specifying @option{-mfp16-format=ieee} selects the IEEE 754-2008 format. |
| This format can represent normalized values in the range of @math{2^{-14}} to 65504. |
| There are 11 bits of significand precision, approximately 3 |
| decimal digits. |
| |
| Specifying @option{-mfp16-format=alternative} selects the ARM |
| alternative format. This representation is similar to the IEEE |
| format, but does not support infinities or NaNs. Instead, the range |
| of exponents is extended, so that this format can represent normalized |
| values in the range of @math{2^{-14}} to 131008. |
| |
| The GCC port for AArch64 only supports the IEEE 754-2008 format, and does |
| not require use of the @option{-mfp16-format} command-line option. |
| |
| The @code{__fp16} type may only be used as an argument to intrinsics defined |
| in @code{<arm_fp16.h>}, or as a storage format. For purposes of |
| arithmetic and other operations, @code{__fp16} values in C or C++ |
| expressions are automatically promoted to @code{float}. |
| |
| The ARM target provides hardware support for conversions between |
| @code{__fp16} and @code{float} values |
| as an extension to VFP and NEON (Advanced SIMD), and from ARMv8-A provides |
| hardware support for conversions between @code{__fp16} and @code{double} |
| values. GCC generates code using these hardware instructions if you |
| compile with options to select an FPU that provides them; |
| for example, @option{-mfpu=neon-fp16 -mfloat-abi=softfp}, |
| in addition to the @option{-mfp16-format} option to select |
| a half-precision format. |
| |
| Language-level support for the @code{__fp16} data type is |
| independent of whether GCC generates code using hardware floating-point |
| instructions. In cases where hardware support is not specified, GCC |
| implements conversions between @code{__fp16} and other types as library |
| calls. |
| |
| It is recommended that portable code use the @code{_Float16} type defined |
| by ISO/IEC TS 18661-3:2015. @xref{Floating Types}. |
| |
| On x86 targets with SSE2 enabled, without @option{-mavx512fp16}, |
| all operations will be emulated by software emulation and the @code{float} |
| instructions. The default behavior for @code{FLT_EVAL_METHOD} is to keep the |
| intermediate result of the operation as 32-bit precision. This may lead to |
| inconsistent behavior between software emulation and AVX512-FP16 instructions. |
| Using @option{-fexcess-precision=16} will force round back after each operation. |
| |
| Using @option{-mavx512fp16} will generate AVX512-FP16 instructions instead of |
| software emulation. The default behavior of @code{FLT_EVAL_METHOD} is to round |
| after each operation. The same is true with @option{-fexcess-precision=standard} |
| and @option{-mfpmath=sse}. If there is no @option{-mfpmath=sse}, |
| @option{-fexcess-precision=standard} alone does the same thing as before, |
| It is useful for code that does not have @code{_Float16} and runs on the x87 |
| FPU. |
| |
| @node Decimal Float |
| @section Decimal Floating Types |
| @cindex decimal floating types |
| @cindex @code{_Decimal32} data type |
| @cindex @code{_Decimal64} data type |
| @cindex @code{_Decimal128} data type |
| @cindex @code{df} integer suffix |
| @cindex @code{dd} integer suffix |
| @cindex @code{dl} integer suffix |
| @cindex @code{DF} integer suffix |
| @cindex @code{DD} integer suffix |
| @cindex @code{DL} integer suffix |
| |
| As an extension, GNU C supports decimal floating types as |
| defined in the N1312 draft of ISO/IEC WDTR24732. Support for decimal |
| floating types in GCC will evolve as the draft technical report changes. |
| Calling conventions for any target might also change. Not all targets |
| support decimal floating types. |
| |
| The decimal floating types are @code{_Decimal32}, @code{_Decimal64}, and |
| @code{_Decimal128}. They use a radix of ten, unlike the floating types |
| @code{float}, @code{double}, and @code{long double} whose radix is not |
| specified by the C standard but is usually two. |
| |
| Support for decimal floating types includes the arithmetic operators |
| add, subtract, multiply, divide; unary arithmetic operators; |
| relational operators; equality operators; and conversions to and from |
| integer and other floating types. Use a suffix @samp{df} or |
| @samp{DF} in a literal constant of type @code{_Decimal32}, @samp{dd} |
| or @samp{DD} for @code{_Decimal64}, and @samp{dl} or @samp{DL} for |
| @code{_Decimal128}. |
| |
| GCC support of decimal float as specified by the draft technical report |
| is incomplete: |
| |
| @itemize @bullet |
| @item |
| When the value of a decimal floating type cannot be represented in the |
| integer type to which it is being converted, the result is undefined |
| rather than the result value specified by the draft technical report. |
| |
| @item |
| GCC does not provide the C library functionality associated with |
| @file{math.h}, @file{fenv.h}, @file{stdio.h}, @file{stdlib.h}, and |
| @file{wchar.h}, which must come from a separate C library implementation. |
| Because of this the GNU C compiler does not define macro |
| @code{__STDC_DEC_FP__} to indicate that the implementation conforms to |
| the technical report. |
| @end itemize |
| |
| Types @code{_Decimal32}, @code{_Decimal64}, and @code{_Decimal128} |
| are supported by the DWARF debug information format. |
| |
| @node Hex Floats |
| @section Hex Floats |
| @cindex hex floats |
| |
| ISO C99 and ISO C++17 support floating-point numbers written not only in |
| the usual decimal notation, such as @code{1.55e1}, but also numbers such as |
| @code{0x1.fp3} written in hexadecimal format. As a GNU extension, GCC |
| supports this in C90 mode (except in some cases when strictly |
| conforming) and in C++98, C++11 and C++14 modes. In that format the |
| @samp{0x} hex introducer and the @samp{p} or @samp{P} exponent field are |
| mandatory. The exponent is a decimal number that indicates the power of |
| 2 by which the significant part is multiplied. Thus @samp{0x1.f} is |
| @tex |
| $1 {15\over16}$, |
| @end tex |
| @ifnottex |
| 1 15/16, |
| @end ifnottex |
| @samp{p3} multiplies it by 8, and the value of @code{0x1.fp3} |
| is the same as @code{1.55e1}. |
| |
| Unlike for floating-point numbers in the decimal notation the exponent |
| is always required in the hexadecimal notation. Otherwise the compiler |
| would not be able to resolve the ambiguity of, e.g., @code{0x1.f}. This |
| could mean @code{1.0f} or @code{1.9375} since @samp{f} is also the |
| extension for floating-point constants of type @code{float}. |
| |
| @node Fixed-Point |
| @section Fixed-Point Types |
| @cindex fixed-point types |
| @cindex @code{_Fract} data type |
| @cindex @code{_Accum} data type |
| @cindex @code{_Sat} data type |
| @cindex @code{hr} fixed-suffix |
| @cindex @code{r} fixed-suffix |
| @cindex @code{lr} fixed-suffix |
| @cindex @code{llr} fixed-suffix |
| @cindex @code{uhr} fixed-suffix |
| @cindex @code{ur} fixed-suffix |
| @cindex @code{ulr} fixed-suffix |
| @cindex @code{ullr} fixed-suffix |
| @cindex @code{hk} fixed-suffix |
| @cindex @code{k} fixed-suffix |
| @cindex @code{lk} fixed-suffix |
| @cindex @code{llk} fixed-suffix |
| @cindex @code{uhk} fixed-suffix |
| @cindex @code{uk} fixed-suffix |
| @cindex @code{ulk} fixed-suffix |
| @cindex @code{ullk} fixed-suffix |
| @cindex @code{HR} fixed-suffix |
| @cindex @code{R} fixed-suffix |
| @cindex @code{LR} fixed-suffix |
| @cindex @code{LLR} fixed-suffix |
| @cindex @code{UHR} fixed-suffix |
| @cindex @code{UR} fixed-suffix |
| @cindex @code{ULR} fixed-suffix |
| @cindex @code{ULLR} fixed-suffix |
| @cindex @code{HK} fixed-suffix |
| @cindex @code{K} fixed-suffix |
| @cindex @code{LK} fixed-suffix |
| @cindex @code{LLK} fixed-suffix |
| @cindex @code{UHK} fixed-suffix |
| @cindex @code{UK} fixed-suffix |
| @cindex @code{ULK} fixed-suffix |
| @cindex @code{ULLK} fixed-suffix |
| |
| As an extension, GNU C supports fixed-point types as |
| defined in the N1169 draft of ISO/IEC DTR 18037. Support for fixed-point |
| types in GCC will evolve as the draft technical report changes. |
| Calling conventions for any target might also change. Not all targets |
| support fixed-point types. |
| |
| The fixed-point types are |
| @code{short _Fract}, |
| @code{_Fract}, |
| @code{long _Fract}, |
| @code{long long _Fract}, |
| @code{unsigned short _Fract}, |
| @code{unsigned _Fract}, |
| @code{unsigned long _Fract}, |
| @code{unsigned long long _Fract}, |
| @code{_Sat short _Fract}, |
| @code{_Sat _Fract}, |
| @code{_Sat long _Fract}, |
| @code{_Sat long long _Fract}, |
| @code{_Sat unsigned short _Fract}, |
| @code{_Sat unsigned _Fract}, |
| @code{_Sat unsigned long _Fract}, |
| @code{_Sat unsigned long long _Fract}, |
| @code{short _Accum}, |
| @code{_Accum}, |
| @code{long _Accum}, |
| @code{long long _Accum}, |
| @code{unsigned short _Accum}, |
| @code{unsigned _Accum}, |
| @code{unsigned long _Accum}, |
| @code{unsigned long long _Accum}, |
| @code{_Sat short _Accum}, |
| @code{_Sat _Accum}, |
| @code{_Sat long _Accum}, |
| @code{_Sat long long _Accum}, |
| @code{_Sat unsigned short _Accum}, |
| @code{_Sat unsigned _Accum}, |
| @code{_Sat unsigned long _Accum}, |
| @code{_Sat unsigned long long _Accum}. |
| |
| Fixed-point data values contain fractional and optional integral parts. |
| The format of fixed-point data varies and depends on the target machine. |
| |
| Support for fixed-point types includes: |
| @itemize @bullet |
| @item |
| prefix and postfix increment and decrement operators (@code{++}, @code{--}) |
| @item |
| unary arithmetic operators (@code{+}, @code{-}, @code{!}) |
| @item |
| binary arithmetic operators (@code{+}, @code{-}, @code{*}, @code{/}) |
| @item |
| binary shift operators (@code{<<}, @code{>>}) |
| @item |
| relational operators (@code{<}, @code{<=}, @code{>=}, @code{>}) |
| @item |
| equality operators (@code{==}, @code{!=}) |
| @item |
| assignment operators (@code{+=}, @code{-=}, @code{*=}, @code{/=}, |
| @code{<<=}, @code{>>=}) |
| @item |
| conversions to and from integer, floating-point, or fixed-point types |
| @end itemize |
| |
| Use a suffix in a fixed-point literal constant: |
| @itemize |
| @item @samp{hr} or @samp{HR} for @code{short _Fract} and |
| @code{_Sat short _Fract} |
| @item @samp{r} or @samp{R} for @code{_Fract} and @code{_Sat _Fract} |
| @item @samp{lr} or @samp{LR} for @code{long _Fract} and |
| @code{_Sat long _Fract} |
| @item @samp{llr} or @samp{LLR} for @code{long long _Fract} and |
| @code{_Sat long long _Fract} |
| @item @samp{uhr} or @samp{UHR} for @code{unsigned short _Fract} and |
| @code{_Sat unsigned short _Fract} |
| @item @samp{ur} or @samp{UR} for @code{unsigned _Fract} and |
| @code{_Sat unsigned _Fract} |
| @item @samp{ulr} or @samp{ULR} for @code{unsigned long _Fract} and |
| @code{_Sat unsigned long _Fract} |
| @item @samp{ullr} or @samp{ULLR} for @code{unsigned long long _Fract} |
| and @code{_Sat unsigned long long _Fract} |
| @item @samp{hk} or @samp{HK} for @code{short _Accum} and |
| @code{_Sat short _Accum} |
| @item @samp{k} or @samp{K} for @code{_Accum} and @code{_Sat _Accum} |
| @item @samp{lk} or @samp{LK} for @code{long _Accum} and |
| @code{_Sat long _Accum} |
| @item @samp{llk} or @samp{LLK} for @code{long long _Accum} and |
| @code{_Sat long long _Accum} |
| @item @samp{uhk} or @samp{UHK} for @code{unsigned short _Accum} and |
| @code{_Sat unsigned short _Accum} |
| @item @samp{uk} or @samp{UK} for @code{unsigned _Accum} and |
| @code{_Sat unsigned _Accum} |
| @item @samp{ulk} or @samp{ULK} for @code{unsigned long _Accum} and |
| @code{_Sat unsigned long _Accum} |
| @item @samp{ullk} or @samp{ULLK} for @code{unsigned long long _Accum} |
| and @code{_Sat unsigned long long _Accum} |
| @end itemize |
| |
| GCC support of fixed-point types as specified by the draft technical report |
| is incomplete: |
| |
| @itemize @bullet |
| @item |
| Pragmas to control overflow and rounding behaviors are not implemented. |
| @end itemize |
| |
| Fixed-point types are supported by the DWARF debug information format. |
| |
| @node Named Address Spaces |
| @section Named Address Spaces |
| @cindex Named Address Spaces |
| |
| As an extension, GNU C supports named address spaces as |
| defined in the N1275 draft of ISO/IEC DTR 18037. Support for named |
| address spaces in GCC will evolve as the draft technical report |
| changes. Calling conventions for any target might also change. At |
| present, only the AVR, M32C, PRU, RL78, and x86 targets support |
| address spaces other than the generic address space. |
| |
| Address space identifiers may be used exactly like any other C type |
| qualifier (e.g., @code{const} or @code{volatile}). See the N1275 |
| document for more details. |
| |
| @anchor{AVR Named Address Spaces} |
| @subsection AVR Named Address Spaces |
| |
| On the AVR target, there are several address spaces that can be used |
| in order to put read-only data into the flash memory and access that |
| data by means of the special instructions @code{LPM} or @code{ELPM} |
| needed to read from flash. |
| |
| Devices belonging to @code{avrtiny} and @code{avrxmega3} can access |
| flash memory by means of @code{LD*} instructions because the flash |
| memory is mapped into the RAM address space. There is @emph{no need} |
| for language extensions like @code{__flash} or attribute |
| @ref{AVR Variable Attributes,,@code{progmem}}. |
| The default linker description files for these devices cater for that |
| feature and @code{.rodata} stays in flash: The compiler just generates |
| @code{LD*} instructions, and the linker script adds core specific |
| offsets to all @code{.rodata} symbols: @code{0x4000} in the case of |
| @code{avrtiny} and @code{0x8000} in the case of @code{avrxmega3}. |
| See @ref{AVR Options} for a list of respective devices. |
| |
| For devices not in @code{avrtiny} or @code{avrxmega3}, |
| any data including read-only data is located in RAM (the generic |
| address space) because flash memory is not visible in the RAM address |
| space. In order to locate read-only data in flash memory @emph{and} |
| to generate the right instructions to access this data without |
| using (inline) assembler code, special address spaces are needed. |
| |
| @table @code |
| @item __flash |
| @cindex @code{__flash} AVR Named Address Spaces |
| The @code{__flash} qualifier locates data in the |
| @code{.progmem.data} section. Data is read using the @code{LPM} |
| instruction. Pointers to this address space are 16 bits wide. |
| |
| @item __flash1 |
| @itemx __flash2 |
| @itemx __flash3 |
| @itemx __flash4 |
| @itemx __flash5 |
| @cindex @code{__flash1} AVR Named Address Spaces |
| @cindex @code{__flash2} AVR Named Address Spaces |
| @cindex @code{__flash3} AVR Named Address Spaces |
| @cindex @code{__flash4} AVR Named Address Spaces |
| @cindex @code{__flash5} AVR Named Address Spaces |
| These are 16-bit address spaces locating data in section |
| @code{.progmem@var{N}.data} where @var{N} refers to |
| address space @code{__flash@var{N}}. |
| The compiler sets the @code{RAMPZ} segment register appropriately |
| before reading data by means of the @code{ELPM} instruction. |
| |
| @item __memx |
| @cindex @code{__memx} AVR Named Address Spaces |
| This is a 24-bit address space that linearizes flash and RAM: |
| If the high bit of the address is set, data is read from |
| RAM using the lower two bytes as RAM address. |
| If the high bit of the address is clear, data is read from flash |
| with @code{RAMPZ} set according to the high byte of the address. |
| @xref{AVR Built-in Functions,,@code{__builtin_avr_flash_segment}}. |
| |
| Objects in this address space are located in @code{.progmemx.data}. |
| @end table |
| |
| @b{Example} |
| |
| @smallexample |
| char my_read (const __flash char ** p) |
| @{ |
| /* p is a pointer to RAM that points to a pointer to flash. |
| The first indirection of p reads that flash pointer |
| from RAM and the second indirection reads a char from this |
| flash address. */ |
| |
| return **p; |
| @} |
| |
| /* Locate array[] in flash memory */ |
| const __flash int array[] = @{ 3, 5, 7, 11, 13, 17, 19 @}; |
| |
| int i = 1; |
| |
| int main (void) |
| @{ |
| /* Return 17 by reading from flash memory */ |
| return array[array[i]]; |
| @} |
| @end smallexample |
| |
| @noindent |
| For each named address space supported by avr-gcc there is an equally |
| named but uppercase built-in macro defined. |
| The purpose is to facilitate testing if respective address space |
| support is available or not: |
| |
| @smallexample |
| #ifdef __FLASH |
| const __flash int var = 1; |
| |
| int read_var (void) |
| @{ |
| return var; |
| @} |
| #else |
| #include <avr/pgmspace.h> /* From AVR-LibC */ |
| |
| const int var PROGMEM = 1; |
| |
| int read_var (void) |
| @{ |
| return (int) pgm_read_word (&var); |
| @} |
| #endif /* __FLASH */ |
| @end smallexample |
| |
| @noindent |
| Notice that attribute @ref{AVR Variable Attributes,,@code{progmem}} |
| locates data in flash but |
| accesses to these data read from generic address space, i.e.@: |
| from RAM, |
| so that you need special accessors like @code{pgm_read_byte} |
| from @w{@uref{http://nongnu.org/avr-libc/user-manual/,AVR-LibC}} |
| together with attribute @code{progmem}. |
| |
| @noindent |
| @b{Limitations and caveats} |
| |
| @itemize |
| @item |
| Reading across the 64@tie{}KiB section boundary of |
| the @code{__flash} or @code{__flash@var{N}} address spaces |
| shows undefined behavior. The only address space that |
| supports reading across the 64@tie{}KiB flash segment boundaries is |
| @code{__memx}. |
| |
| @item |
| If you use one of the @code{__flash@var{N}} address spaces |
| you must arrange your linker script to locate the |
| @code{.progmem@var{N}.data} sections according to your needs. |
| |
| @item |
| Any data or pointers to the non-generic address spaces must |
| be qualified as @code{const}, i.e.@: as read-only data. |
| This still applies if the data in one of these address |
| spaces like software version number or calibration lookup table are intended to |
| be changed after load time by, say, a boot loader. In this case |
| the right qualification is @code{const} @code{volatile} so that the compiler |
| must not optimize away known values or insert them |
| as immediates into operands of instructions. |
| |
| @item |
| The following code initializes a variable @code{pfoo} |
| located in static storage with a 24-bit address: |
| @smallexample |
| extern const __memx char foo; |
| const __memx void *pfoo = &foo; |
| @end smallexample |
| |
| @item |
| On the reduced Tiny devices like ATtiny40, no address spaces are supported. |
| Just use vanilla C / C++ code without overhead as outlined above. |
| Attribute @code{progmem} is supported but works differently, |
| see @ref{AVR Variable Attributes}. |
| |
| @end itemize |
| |
| @subsection M32C Named Address Spaces |
| @cindex @code{__far} M32C Named Address Spaces |
| |
| On the M32C target, with the R8C and M16C CPU variants, variables |
| qualified with @code{__far} are accessed using 32-bit addresses in |
| order to access memory beyond the first 64@tie{}Ki bytes. If |
| @code{__far} is used with the M32CM or M32C CPU variants, it has no |
| effect. |
| |
| @subsection PRU Named Address Spaces |
| @cindex @code{__regio_symbol} PRU Named Address Spaces |
| |
| On the PRU target, variables qualified with @code{__regio_symbol} are |
| aliases used to access the special I/O CPU registers. They must be |
| declared as @code{extern} because such variables will not be allocated in |
| any data memory. They must also be marked as @code{volatile}, and can |
| only be 32-bit integer types. The only names those variables can have |
| are @code{__R30} and @code{__R31}, representing respectively the |
| @code{R30} and @code{R31} special I/O CPU registers. Hence the following |
| example is the only valid usage of @code{__regio_symbol}: |
| |
| @smallexample |
| extern volatile __regio_symbol uint32_t __R30; |
| extern volatile __regio_symbol uint32_t __R31; |
| @end smallexample |
| |
| @subsection RL78 Named Address Spaces |
| @cindex @code{__far} RL78 Named Address Spaces |
| |
| On the RL78 target, variables qualified with @code{__far} are accessed |
| with 32-bit pointers (20-bit addresses) rather than the default 16-bit |
| addresses. Non-far variables are assumed to appear in the topmost |
| 64@tie{}KiB of the address space. |
| |
| @subsection x86 Named Address Spaces |
| @cindex x86 named address spaces |
| |
| On the x86 target, variables may be declared as being relative |
| to the @code{%fs} or @code{%gs} segments. |
| |
| @table @code |
| @item __seg_fs |
| @itemx __seg_gs |
| @cindex @code{__seg_fs} x86 named address space |
| @cindex @code{__seg_gs} x86 named address space |
| The object is accessed with the respective segment override prefix. |
| |
| The respective segment base must be set via some method specific to |
| the operating system. Rather than require an expensive system call |
| to retrieve the segment base, these address spaces are not considered |
| to be subspaces of the generic (flat) address space. This means that |
| explicit casts are required to convert pointers between these address |
| spaces and the generic address space. In practice the application |
| should cast to @code{uintptr_t} and apply the segment base offset |
| that it installed previously. |
| |
| The preprocessor symbols @code{__SEG_FS} and @code{__SEG_GS} are |
| defined when these address spaces are supported. |
| @end table |
| |
| @node Zero Length |
| @section Arrays of Length Zero |
| @cindex arrays of length zero |
| @cindex zero-length arrays |
| @cindex length-zero arrays |
| @cindex flexible array members |
| |
| Declaring zero-length arrays is allowed in GNU C as an extension. |
| A zero-length array can be useful as the last element of a structure |
| that is really a header for a variable-length object: |
| |
| @smallexample |
| struct line @{ |
| int length; |
| char contents[0]; |
| @}; |
| |
| struct line *thisline = (struct line *) |
| malloc (sizeof (struct line) + this_length); |
| thisline->length = this_length; |
| @end smallexample |
| |
| Although the size of a zero-length array is zero, an array member of |
| this kind may increase the size of the enclosing type as a result of tail |
| padding. The offset of a zero-length array member from the beginning |
| of the enclosing structure is the same as the offset of an array with |
| one or more elements of the same type. The alignment of a zero-length |
| array is the same as the alignment of its elements. |
| |
| Declaring zero-length arrays in other contexts, including as interior |
| members of structure objects or as non-member objects, is discouraged. |
| Accessing elements of zero-length arrays declared in such contexts is |
| undefined and may be diagnosed. |
| |
| In the absence of the zero-length array extension, in ISO C90 |
| the @code{contents} array in the example above would typically be declared |
| to have a single element. Unlike a zero-length array which only contributes |
| to the size of the enclosing structure for the purposes of alignment, |
| a one-element array always occupies at least as much space as a single |
| object of the type. Although using one-element arrays this way is |
| discouraged, GCC handles accesses to trailing one-element array members |
| analogously to zero-length arrays. |
| |
| The preferred mechanism to declare variable-length types like |
| @code{struct line} above is the ISO C99 @dfn{flexible array member}, |
| with slightly different syntax and semantics: |
| |
| @itemize @bullet |
| @item |
| Flexible array members are written as @code{contents[]} without |
| the @code{0}. |
| |
| @item |
| Flexible array members have incomplete type, and so the @code{sizeof} |
| operator may not be applied. As a quirk of the original implementation |
| of zero-length arrays, @code{sizeof} evaluates to zero. |
| |
| @item |
| Flexible array members may only appear as the last member of a |
| @code{struct} that is otherwise non-empty. |
| |
| @item |
| A structure containing a flexible array member, or a union containing |
| such a structure (possibly recursively), may not be a member of a |
| structure or an element of an array. (However, these uses are |
| permitted by GCC as extensions.) |
| @end itemize |
| |
| Non-empty initialization of zero-length |
| arrays is treated like any case where there are more initializer |
| elements than the array holds, in that a suitable warning about ``excess |
| elements in array'' is given, and the excess elements (all of them, in |
| this case) are ignored. |
| |
| GCC allows static initialization of flexible array members. |
| This is equivalent to defining a new structure containing the original |
| structure followed by an array of sufficient size to contain the data. |
| E.g.@: in the following, @code{f1} is constructed as if it were declared |
| like @code{f2}. |
| |
| @smallexample |
| struct f1 @{ |
| int x; int y[]; |
| @} f1 = @{ 1, @{ 2, 3, 4 @} @}; |
| |
| struct f2 @{ |
| struct f1 f1; int data[3]; |
| @} f2 = @{ @{ 1 @}, @{ 2, 3, 4 @} @}; |
| @end smallexample |
| |
| @noindent |
| The convenience of this extension is that @code{f1} has the desired |
| type, eliminating the need to consistently refer to @code{f2.f1}. |
| |
| This has symmetry with normal static arrays, in that an array of |
| unknown size is also written with @code{[]}. |
| |
| Of course, this extension only makes sense if the extra data comes at |
| the end of a top-level object, as otherwise we would be overwriting |
| data at subsequent offsets. To avoid undue complication and confusion |
| with initialization of deeply nested arrays, we simply disallow any |
| non-empty initialization except when the structure is the top-level |
| object. For example: |
| |
| @smallexample |
| struct foo @{ int x; int y[]; @}; |
| struct bar @{ struct foo z; @}; |
| |
| struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.} |
| struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.} |
| struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.} |
| struct foo d[1] = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.} |
| @end smallexample |
| |
| @node Empty Structures |
| @section Structures with No Members |
| @cindex empty structures |
| @cindex zero-size structures |
| |
| GCC permits a C structure to have no members: |
| |
| @smallexample |
| struct empty @{ |
| @}; |
| @end smallexample |
| |
| The structure has size zero. In C++, empty structures are part |
| of the language. G++ treats empty structures as if they had a single |
| member of type @code{char}. |
| |
| @node Variable Length |
| @section Arrays of Variable Length |
| @cindex variable-length arrays |
| @cindex arrays of variable length |
| @cindex VLAs |
| |
| Variable-length automatic arrays are allowed in ISO C99, and as an |
| extension GCC accepts them in C90 mode and in C++. These arrays are |
| declared like any other automatic arrays, but with a length that is not |
| a constant expression. The storage is allocated at the point of |
| declaration and deallocated when the block scope containing the declaration |
| exits. For |
| example: |
| |
| @smallexample |
| FILE * |
| concat_fopen (char *s1, char *s2, char *mode) |
| @{ |
| char str[strlen (s1) + strlen (s2) + 1]; |
| strcpy (str, s1); |
| strcat (str, s2); |
| return fopen (str, mode); |
| @} |
| @end smallexample |
| |
| @cindex scope of a variable length array |
| @cindex variable-length array scope |
| @cindex deallocating variable length arrays |
| Jumping or breaking out of the scope of the array name deallocates the |
| storage. Jumping into the scope is not allowed; you get an error |
| message for it. |
| |
| @cindex variable-length array in a structure |
| As an extension, GCC accepts variable-length arrays as a member of |
| a structure or a union. For example: |
| |
| @smallexample |
| void |
| foo (int n) |
| @{ |
| struct S @{ int x[n]; @}; |
| @} |
| @end smallexample |
| |
| @cindex @code{alloca} vs variable-length arrays |
| You can use the function @code{alloca} to get an effect much like |
| variable-length arrays. The function @code{alloca} is available in |
| many other C implementations (but not in all). On the other hand, |
| variable-length arrays are more elegant. |
| |
| There are other differences between these two methods. Space allocated |
| with @code{alloca} exists until the containing @emph{function} returns. |
| The space for a variable-length array is deallocated as soon as the array |
| name's scope ends, unless you also use @code{alloca} in this scope. |
| |
| You can also use variable-length arrays as arguments to functions: |
| |
| @smallexample |
| struct entry |
| tester (int len, char data[len][len]) |
| @{ |
| /* @r{@dots{}} */ |
| @} |
| @end smallexample |
| |
| The length of an array is computed once when the storage is allocated |
| and is remembered for the scope of the array in case you access it with |
| @code{sizeof}. |
| |
| If you want to pass the array first and the length afterward, you can |
| use a forward declaration in the parameter list---another GNU extension. |
| |
| @smallexample |
| struct entry |
| tester (int len; char data[len][len], int len) |
| @{ |
| /* @r{@dots{}} */ |
| @} |
| @end smallexample |
| |
| @cindex parameter forward declaration |
| The @samp{int len} before the semicolon is a @dfn{parameter forward |
| declaration}, and it serves the purpose of making the name @code{len} |
| known when the declaration of @code{data} is parsed. |
| |
| You can write any number of such parameter forward declarations in the |
| parameter list. They can be separated by commas or semicolons, but the |
| last one must end with a semicolon, which is followed by the ``real'' |
| parameter declarations. Each forward declaration must match a ``real'' |
| declaration in parameter name and data type. ISO C99 does not support |
| parameter forward declarations. |
| |
| @node Variadic Macros |
| @section Macros with a Variable Number of Arguments. |
| @cindex variable number of arguments |
| @cindex macro with variable arguments |
| @cindex rest argument (in macro) |
| @cindex variadic macros |
| |
| In the ISO C standard of 1999, a macro can be declared to accept a |
| variable number of arguments much as a function can. The syntax for |
| defining the macro is similar to that of a function. Here is an |
| example: |
| |
| @smallexample |
| #define debug(format, ...) fprintf (stderr, format, __VA_ARGS__) |
| @end smallexample |
| |
| @noindent |
| Here @samp{@dots{}} is a @dfn{variable argument}. In the invocation of |
| such a macro, it represents the zero or more tokens until the closing |
| parenthesis that ends the invocation, including any commas. This set of |
| tokens replaces the identifier @code{__VA_ARGS__} in the macro body |
| wherever it appears. See the CPP manual for more information. |
| |
| GCC has long supported variadic macros, and used a different syntax that |
| allowed you to give a name to the variable arguments just like any other |
| argument. Here is an example: |
| |
| @smallexample |
| #define debug(format, args...) fprintf (stderr, format, args) |
| @end smallexample |
| |
| @noindent |
| This is in all ways equivalent to the ISO C example above, but arguably |
| more readable and descriptive. |
| |
| GNU CPP has two further variadic macro extensions, and permits them to |
| be used with either of the above forms of macro definition. |
| |
| In standard C, you are not allowed to leave the variable argument out |
| entirely; but you are allowed to pass an empty argument. For example, |
| this invocation is invalid in ISO C, because there is no comma after |
| the string: |
| |
| @smallexample |
| debug ("A message") |
| @end smallexample |
| |
| GNU CPP permits you to completely omit the variable arguments in this |
| way. In the above examples, the compiler would complain, though since |
| the expansion of the macro still has the extra comma after the format |
| string. |
| |
| To help solve this problem, CPP behaves specially for variable arguments |
| used with the token paste operator, @samp{##}. If instead you write |
| |
| @smallexample |
| #define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__) |
| @end smallexample |
| |
| @noindent |
| and if the variable arguments are omitted or empty, the @samp{##} |
| operator causes the preprocessor to remove the comma before it. If you |
| do provide some variable arguments in your macro invocation, GNU CPP |
| does not complain about the paste operation and instead places the |
| variable arguments after the comma. Just like any other pasted macro |
| argument, these arguments are not macro expanded. |
| |
| @node Escaped Newlines |
| @section Slightly Looser Rules for Escaped Newlines |
| @cindex escaped newlines |
| @cindex newlines (escaped) |
| |
| The preprocessor treatment of escaped newlines is more relaxed |
| than that specified by the C90 standard, which requires the newline |
| to immediately follow a backslash. |
| GCC's implementation allows whitespace in the form |
| of spaces, horizontal and vertical tabs, and form feeds between the |
| backslash and the subsequent newline. The preprocessor issues a |
| warning, but treats it as a valid escaped newline and combines the two |
| lines to form a single logical line. This works within comments and |
| tokens, as well as between tokens. Comments are @emph{not} treated as |
| whitespace for the purposes of this relaxation, since they have not |
| yet been replaced with spaces. |
| |
| @node Subscripting |
| @section Non-Lvalue Arrays May Have Subscripts |
| @cindex subscripting |
| @cindex arrays, non-lvalue |
| |
| @cindex subscripting and function values |
| In ISO C99, arrays that are not lvalues still decay to pointers, and |
| may be subscripted, although they may not be modified or used after |
| the next sequence point and the unary @samp{&} operator may not be |
| applied to them. As an extension, GNU C allows such arrays to be |
| subscripted in C90 mode, though otherwise they do not decay to |
| pointers outside C99 mode. For example, |
| this is valid in GNU C though not valid in C90: |
| |
| @smallexample |
| @group |
| struct foo @{int a[4];@}; |
| |
| struct foo f(); |
| |
| bar (int index) |
| @{ |
| return f().a[index]; |
| @} |
| @end group |
| @end smallexample |
| |
| @node Pointer Arith |
| @section Arithmetic on @code{void}- and Function-Pointers |
| @cindex void pointers, arithmetic |
| @cindex void, size of pointer to |
| @cindex function pointers, arithmetic |
| @cindex function, size of pointer to |
| |
| In GNU C, addition and subtraction operations are supported on pointers to |
| @code{void} and on pointers to functions. This is done by treating the |
| size of a @code{void} or of a function as 1. |
| |
| A consequence of this is that @code{sizeof} is also allowed on @code{void} |
| and on function types, and returns 1. |
| |
| @opindex Wpointer-arith |
| The option @option{-Wpointer-arith} requests a warning if these extensions |
| are used. |
| |
| @node Variadic Pointer Args |
| @section Pointer Arguments in Variadic Functions |
| @cindex pointer arguments in variadic functions |
| @cindex variadic functions, pointer arguments |
| |
| Standard C requires that pointer types used with @code{va_arg} in |
| functions with variable argument lists either must be compatible with |
| that of the actual argument, or that one type must be a pointer to |
| @code{void} and the other a pointer to a character type. GNU C |
| implements the POSIX XSI extension that additionally permits the use |
| of @code{va_arg} with a pointer type to receive arguments of any other |
| pointer type. |
| |
| In particular, in GNU C @samp{va_arg (ap, void *)} can safely be used |
| to consume an argument of any pointer type. |
| |
| @node Pointers to Arrays |
| @section Pointers to Arrays with Qualifiers Work as Expected |
| @cindex pointers to arrays |
| @cindex const qualifier |
| |
| In GNU C, pointers to arrays with qualifiers work similar to pointers |
| to other qualified types. For example, a value of type @code{int (*)[5]} |
| can be used to initialize a variable of type @code{const int (*)[5]}. |
| These types are incompatible in ISO C because the @code{const} qualifier |
| is formally attached to the element type of the array and not the |
| array itself. |
| |
| @smallexample |
| extern void |
| transpose (int N, int M, double out[M][N], const double in[N][M]); |
| double x[3][2]; |
| double y[2][3]; |
| @r{@dots{}} |
| transpose(3, 2, y, x); |
| @end smallexample |
| |
| @node Initializers |
| @section Non-Constant Initializers |
| @cindex initializers, non-constant |
| @cindex non-constant initializers |
| |
| As in standard C++ and ISO C99, the elements of an aggregate initializer for an |
| automatic variable are not required to be constant expressions in GNU C@. |
| Here is an example of an initializer with run-time varying elements: |
| |
| @smallexample |
| foo (float f, float g) |
| @{ |
| float beat_freqs[2] = @{ f-g, f+g @}; |
| /* @r{@dots{}} */ |
| @} |
| @end smallexample |
| |
| @node Compound Literals |
| @section Compound Literals |
| @cindex constructor expressions |
| @cindex initializations in expressions |
| @cindex structures, constructor expression |
| @cindex expressions, constructor |
| @cindex compound literals |
| @c The GNU C name for what C99 calls compound literals was "constructor expressions". |
| |
| A compound literal looks like a cast of a brace-enclosed aggregate |
| initializer list. Its value is an object of the type specified in |
| the cast, containing the elements specified in the initializer. |
| Unlike the result of a cast, a compound literal is an lvalue. ISO |
| C99 and later support compound literals. As an extension, GCC |
| supports compound literals also in C90 mode and in C++, although |
| as explained below, the C++ semantics are somewhat different. |
| |
| Usually, the specified type of a compound literal is a structure. Assume |
| that @code{struct foo} and @code{structure} are declared as shown: |
| |
| @smallexample |
| struct foo @{int a; char b[2];@} structure; |
| @end smallexample |
| |
| @noindent |
| Here is an example of constructing a @code{struct foo} with a compound literal: |
| |
| @smallexample |
| structure = ((struct foo) @{x + y, 'a', 0@}); |
| @end smallexample |
| |
| @noindent |
| This is equivalent to writing the following: |
| |
| @smallexample |
| @{ |
| struct foo temp = @{x + y, 'a', 0@}; |
| structure = temp; |
| @} |
| @end smallexample |
| |
| You can also construct an array, though this is dangerous in C++, as |
| explained below. If all the elements of the compound literal are |
| (made up of) simple constant expressions suitable for use in |
| initializers of objects of static storage duration, then the compound |
| literal can be coerced to a pointer to its first element and used in |
| such an initializer, as shown here: |
| |
| @smallexample |
| char **foo = (char *[]) @{ "x", "y", "z" @}; |
| @end smallexample |
| |
| Compound literals for scalar types and union types are also allowed. In |
| the following example the variable @code{i} is initialized to the value |
| @code{2}, the result of incrementing the unnamed object created by |
| the compound literal. |
| |
| @smallexample |
| int i = ++(int) @{ 1 @}; |
| @end smallexample |
| |
| As a GNU extension, GCC allows initialization of objects with static storage |
| duration by compound literals (which is not possible in ISO C99 because |
| the initializer is not a constant). |
| It is handled as if the object were initialized only with the brace-enclosed |
| list if the types of the compound literal and the object match. |
| The elements of the compound literal must be constant. |
| If the object being initialized has array type of unknown size, the size is |
| determined by the size of the compound literal. |
| |
| @smallexample |
| static struct foo x = (struct foo) @{1, 'a', 'b'@}; |
| static int y[] = (int []) @{1, 2, 3@}; |
| static int z[] = (int [3]) @{1@}; |
| @end smallexample |
| |
| @noindent |
| The above lines are equivalent to the following: |
| @smallexample |
| static struct foo x = @{1, 'a', 'b'@}; |
| static int y[] = @{1, 2, 3@}; |
| static int z[] = @{1, 0, 0@}; |
| @end smallexample |
| |
| In C, a compound literal designates an unnamed object with static or |
| automatic storage duration. In C++, a compound literal designates a |
| temporary object that only lives until the end of its full-expression. |
| As a result, well-defined C code that takes the address of a subobject |
| of a compound literal can be undefined in C++, so G++ rejects |
| the conversion of a temporary array to a pointer. For instance, if |
| the array compound literal example above appeared inside a function, |
| any subsequent use of @code{foo} in C++ would have undefined behavior |
| because the lifetime of the array ends after the declaration of @code{foo}. |
| |
| As an optimization, G++ sometimes gives array compound literals longer |
| lifetimes: when the array either appears outside a function or has |
| a @code{const}-qualified type. If @code{foo} and its initializer had |
| elements of type @code{char *const} rather than @code{char *}, or if |
| @code{foo} were a global variable, the array would have static storage |
| duration. But it is probably safest just to avoid the use of array |
| compound literals in C++ code. |
| |
| @node Designated Inits |
| @section Designated Initializers |
| @cindex initializers with labeled elements |
| @cindex labeled elements in initializers |
| @cindex case labels in initializers |
| @cindex designated initializers |
| |
| Standard C90 requires the elements of an initializer to appear in a fixed |
| order, the same as the order of the elements in the array or structure |
| being initialized. |
| |
| In ISO C99 you can give the elements in any order, specifying the array |
| indices or structure field names they apply to, and GNU C allows this as |
| an extension in C90 mode as well. This extension is not |
| implemented in GNU C++. |
| |
| To specify an array index, write |
| @samp{[@var{index}] =} before the element value. For example, |
| |
| @smallexample |
| int a[6] = @{ [4] = 29, [2] = 15 @}; |
| @end smallexample |
| |
| @noindent |
| is equivalent to |
| |
| @smallexample |
| int a[6] = @{ 0, 0, 15, 0, 29, 0 @}; |
| @end smallexample |
| |
| @noindent |
| The index values must be constant expressions, even if the array being |
| initialized is automatic. |
| |
| An alternative syntax for this that has been obsolete since GCC 2.5 but |
| GCC still accepts is to write @samp{[@var{index}]} before the element |
| value, with no @samp{=}. |
| |
| To initialize a range of elements to the same value, write |
| @samp{[@var{first} ... @var{last}] = @var{value}}. This is a GNU |
| extension. For example, |
| |
| @smallexample |
| int widths[] = @{ [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 @}; |
| @end smallexample |
| |
| @noindent |
| If the value in it has side effects, the side effects happen only once, |
| not for each initialized field by the range initializer. |
| |
| @noindent |
| Note that the length of the array is the highest value specified |
| plus one. |
| |
| In a structure initializer, specify the name of a field to initialize |
| with @samp{.@var{fieldname} =} before the element value. For example, |
| given the following structure, |
| |
| @smallexample |
| struct point @{ int x, y; @}; |
| @end smallexample |
| |
| @noindent |
| the following initialization |
| |
| @smallexample |
| struct point p = @{ .y = yvalue, .x = xvalue @}; |
| @end smallexample |
| |
| @noindent |
| is equivalent to |
| |
| @smallexample |
| struct point p = @{ xvalue, yvalue @}; |
| @end smallexample |
| |
| Another syntax that has the same meaning, obsolete since GCC 2.5, is |
| @samp{@var{fieldname}:}, as shown here: |
| |
| @smallexample |
| struct point p = @{ y: yvalue, x: xvalue @}; |
| @end smallexample |
| |
| Omitted fields are implicitly initialized the same as for objects |
| that have static storage duration. |
| |
| @cindex designators |
| The @samp{[@var{index}]} or @samp{.@var{fieldname}} is known as a |
| @dfn{designator}. You can also use a designator (or the obsolete colon |
| syntax) when initializing a union, to specify which element of the union |
| should be used. For example, |
| |
| @smallexample |
| union foo @{ int i; double d; @}; |
| |
| union foo f = @{ .d = 4 @}; |
| @end smallexample |
| |
| @noindent |
| converts 4 to a @code{double} to store it in the union using |
| the second element. By contrast, casting 4 to type @code{union foo} |
| stores it into the union as the integer @code{i}, since it is |
| an integer. @xref{Cast to Union}. |
| |
| You can combine this technique of naming elements with ordinary C |
| initialization of successive elements. Each initializer element that |
| does not have a designator applies to the next consecutive element of the |
| array or structure. For example, |
| |
| @smallexample |
| int a[6] = @{ [1] = v1, v2, [4] = v4 @}; |
| @end smallexample |
| |
| @noindent |
| is equivalent to |
| |
| @smallexample |
| int a[6] = @{ 0, v1, v2, 0, v4, 0 @}; |
| @end smallexample |
| |
| Labeling the elements of an array initializer is especially useful |
| when the indices are characters or belong to an @code{enum} type. |
| For example: |
| |
| @smallexample |
| int whitespace[256] |
| = @{ [' '] = 1, ['\t'] = 1, ['\h'] = 1, |
| ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 @}; |
| @end smallexample |
| |
| @cindex designator lists |
| You can also write a series of @samp{.@var{fieldname}} and |
| @samp{[@var{index}]} designators before an @samp{=} to specify a |
| nested subobject to initialize; the list is taken relative to the |
| subobject corresponding to the closest surrounding brace pair. For |
| example, with the @samp{struct point} declaration above: |
| |
| @smallexample |
| struct point ptarray[10] = @{ [2].y = yv2, [2].x = xv2, [0].x = xv0 @}; |
| @end smallexample |
| |
| If the same field is initialized multiple times, or overlapping |
| fields of a union are initialized, the value from the last |
| initialization is used. When a field of a union is itself a structure, |
| the entire structure from the last field initialized is used. If any previous |
| initializer has side effect, it is unspecified whether the side effect |
| happens or not. Currently, GCC discards the side-effecting |
| initializer expressions and issues a warning. |
| |
| @node Case Ranges |
| @section Case Ranges |
| @cindex case ranges |
| @cindex ranges in case statements |
| |
| You can specify a range of consecutive values in a single @code{case} label, |
| like this: |
| |
| @smallexample |
| case @var{low} ... @var{high}: |
| @end smallexample |
| |
| @noindent |
| This has the same effect as the proper number of individual @code{case} |
| labels, one for each integer value from @var{low} to @var{high}, inclusive. |
| |
| This feature is especially useful for ranges of ASCII character codes: |
| |
| @smallexample |
| case 'A' ... 'Z': |
| @end smallexample |
| |
| @strong{Be careful:} Write spaces around the @code{...}, for otherwise |
| it may be parsed wrong when you use it with integer values. For example, |
| write this: |
| |
| @smallexample |
| case 1 ... 5: |
| @end smallexample |
| |
| @noindent |
| rather than this: |
| |
| @smallexample |
| case 1...5: |
| @end smallexample |
| |
| @node Cast to Union |
| @section Cast to a Union Type |
| @cindex cast to a union |
| @cindex union, casting to a |
| |
| A cast to a union type is a C extension not available in C++. It looks |
| just like ordinary casts with the constraint that the type specified is |
| a union type. You can specify the type either with the @code{union} |
| keyword or with a @code{typedef} name that refers to a union. The result |
| of a cast to a union is a temporary rvalue of the union type with a member |
| whose type matches that of the operand initialized to the value of |
| the operand. The effect of a cast to a union is similar to a compound |
| literal except that it yields an rvalue like standard casts do. |
| @xref{Compound Literals}. |
| |
| Expressions that may be cast to the union type are those whose type matches |
| at least one of the members of the union. Thus, given the following union |
| and variables: |
| |
| @smallexample |
| union foo @{ int i; double d; @}; |
| int x; |
| double y; |
| union foo z; |
| @end smallexample |
| |
| @noindent |
| both @code{x} and @code{y} can be cast to type @code{union foo} and |
| the following assignments |
| @smallexample |
| z = (union foo) x; |
| z = (union foo) y; |
| @end smallexample |
| are shorthand equivalents of these |
| @smallexample |
| z = (union foo) @{ .i = x @}; |
| z = (union foo) @{ .d = y @}; |
| @end smallexample |
| |
| However, @code{(union foo) FLT_MAX;} is not a valid cast because the union |
| has no member of type @code{float}. |
| |
| Using the cast as the right-hand side of an assignment to a variable of |
| union type is equivalent to storing in a member of the union with |
| the same type |
| |
| @smallexample |
| union foo u; |
| /* @r{@dots{}} */ |
| u = (union foo) x @equiv{} u.i = x |
| u = (union foo) y @equiv{} u.d = y |
| @end smallexample |
| |
| You can also use the union cast as a function argument: |
| |
| @smallexample |
| void hack (union foo); |
| /* @r{@dots{}} */ |
| hack ((union foo) x); |
| @end smallexample |
| |
| @node Mixed Labels and Declarations |
| @section Mixed Declarations, Labels and Code |
| @cindex mixed declarations and code |
| @cindex declarations, mixed with code |
| @cindex code, mixed with declarations |
| |
| ISO C99 and ISO C++ allow declarations and code to be freely mixed |
| within compound statements. ISO C2X allows labels to be |
| placed before declarations and at the end of a compound statement. |
| As an extension, GNU C also allows all this in C90 mode. For example, |
| you could do: |
| |
| @smallexample |
| int i; |
| /* @r{@dots{}} */ |
| i++; |
| int j = i + 2; |
| @end smallexample |
| |
| Each identifier is visible from where it is declared until the end of |
| the enclosing block. |
| |
| @node Function Attributes |
| @section Declaring Attributes of Functions |
| @cindex function attributes |
| @cindex declaring attributes of functions |
| @cindex @code{volatile} applied to function |
| @cindex @code{const} applied to function |
| |
| In GNU C and C++, you can use function attributes to specify certain |
| function properties that may help the compiler optimize calls or |
| check code more carefully for correctness. For example, you |
| can use attributes to specify that a function never returns |
| (@code{noreturn}), returns a value depending only on the values of |
| its arguments (@code{const}), or has @code{printf}-style arguments |
| (@code{format}). |
| |
| You can also use attributes to control memory placement, code |
| generation options or call/return conventions within the function |
| being annotated. Many of these attributes are target-specific. For |
| example, many targets support attributes for defining interrupt |
| handler functions, which typically must follow special register usage |
| and return conventions. Such attributes are described in the subsection |
| for each target. However, a considerable number of attributes are |
| supported by most, if not all targets. Those are described in |
| the @ref{Common Function Attributes} section. |
| |
| Function attributes are introduced by the @code{__attribute__} keyword |
| in the declaration of a function, followed by an attribute specification |
| enclosed in double parentheses. You can specify multiple attributes in |
| a declaration by separating them by commas within the double parentheses |
| or by immediately following one attribute specification with another. |
| @xref{Attribute Syntax}, for the exact rules on attribute syntax and |
| placement. Compatible attribute specifications on distinct declarations |
| of the same function are merged. An attribute specification that is not |
| compatible with attributes already applied to a declaration of the same |
| function is ignored with a warning. |
| |
| Some function attributes take one or more arguments that refer to |
| the function's parameters by their positions within the function parameter |
| list. Such attribute arguments are referred to as @dfn{positional arguments}. |
| Unless specified otherwise, positional arguments that specify properties |
| of parameters with pointer types can also specify the same properties of |
| the implicit C++ @code{this} argument in non-static member functions, and |
| of parameters of reference to a pointer type. For ordinary functions, |
| position one refers to the first parameter on the list. In C++ non-static |
| member functions, position one refers to the implicit @code{this} pointer. |
| The same restrictions and effects apply to function attributes used with |
| ordinary functions or C++ member functions. |
| |
| GCC also supports attributes on |
| variable declarations (@pxref{Variable Attributes}), |
| labels (@pxref{Label Attributes}), |
| enumerators (@pxref{Enumerator Attributes}), |
| statements (@pxref{Statement Attributes}), |
| types (@pxref{Type Attributes}), |
| and on field declarations (for @code{tainted_args}). |
| |
| There is some overlap between the purposes of attributes and pragmas |
| (@pxref{Pragmas,,Pragmas Accepted by GCC}). It has been |
| found convenient to use @code{__attribute__} to achieve a natural |
| attachment of attributes to their corresponding declarations, whereas |
| @code{#pragma} is of use for compatibility with other compilers |
| or constructs that do not naturally form part of the grammar. |
| |
| In addition to the attributes documented here, |
| GCC plugins may provide their own attributes. |
| |
| @menu |
| * Common Function Attributes:: |
| * AArch64 Function Attributes:: |
| * AMD GCN Function Attributes:: |
| * ARC Function Attributes:: |
| * ARM Function Attributes:: |
| * AVR Function Attributes:: |
| * Blackfin Function Attributes:: |
| * BPF Function Attributes:: |
| * CR16 Function Attributes:: |
| * C-SKY Function Attributes:: |
| * Epiphany Function Attributes:: |
| * H8/300 Function Attributes:: |
| * IA-64 Function Attributes:: |
| * M32C Function Attributes:: |
| * M32R/D Function Attributes:: |
| * m68k Function Attributes:: |
| * MCORE Function Attributes:: |
| * MeP Function Attributes:: |
| * MicroBlaze Function Attributes:: |
| * Microsoft Windows Function Attributes:: |
| * MIPS Function Attributes:: |
| * MSP430 Function Attributes:: |
| * NDS32 Function Attributes:: |
| * Nios II Function Attributes:: |
| * Nvidia PTX Function Attributes:: |
| * PowerPC Function Attributes:: |
| * RISC-V Function Attributes:: |
| * RL78 Function Attributes:: |
| * RX Function Attributes:: |
| * S/390 Function Attributes:: |
| * SH Function Attributes:: |
| * Symbian OS Function Attributes:: |
| * V850 Function Attributes:: |
| * Visium Function Attributes:: |
| * x86 Function Attributes:: |
| * Xstormy16 Function Attributes:: |
| @end menu |
| |
| @node Common Function Attributes |
| @subsection Common Function Attributes |
| |
| The following attributes are supported on most targets. |
| |
| @table @code |
| @c Keep this table alphabetized by attribute name. Treat _ as space. |
| |
| @item access (@var{access-mode}, @var{ref-index}) |
| @itemx access (@var{access-mode}, @var{ref-index}, @var{size-index}) |
| |
| The @code{access} attribute enables the detection of invalid or unsafe |
| accesses by functions to which they apply 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 @option{-Wstringop-overflow}, |
| @option{-Wuninitialized}, @option{-Wunused}, and others. |
| |
| The @code{access} attribute specifies that a function to whose by-reference |
| arguments the attribute applies accesses the referenced object according to |
| @var{access-mode}. The @var{access-mode} argument is required and must be |
| one of four names: @code{read_only}, @code{read_write}, @code{write_only}, |
| or @code{none}. The remaining two are positional arguments. |
| |
| The required @var{ref-index} positional argument denotes a function |
| argument of pointer (or in C++, reference) type that is subject to |
| the access. The same pointer argument can be referenced by at most one |
| distinct @code{access} attribute. |
| |
| The optional @var{size-index} positional argument denotes 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 @var{ref-index}, |
| or the number of bytes when the pointer type is @code{void*}. When no |
| @var{size-index} argument is specified, the pointer argument must be either |
| null or point to a space that is suitably aligned and large 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 @code{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 @var{size-index} |
| is zero, the referenced object must be initialized. The mode implies |
| a stronger guarantee than the @code{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 @code{read_only} access mode is the argument to |
| the @code{puts} function, or the second and third arguments to |
| the @code{memcpy} function. |
| |
| @smallexample |
| __attribute__ ((access (read_only, 1))) int puts (const char*); |
| __attribute__ ((access (read_only, 2, 3))) void* memcpy (void*, const void*, size_t); |
| @end smallexample |
| |
| The @code{read_write} access mode applies to arguments of pointer types |
| without the @code{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 @var{size-index} |
| is zero, the object referenced by the pointer must be initialized. An example |
| of the use of the @code{read_write} access mode is the first argument to |
| the @code{strcat} function. |
| |
| @smallexample |
| __attribute__ ((access (read_write, 1), access (read_only, 2))) char* strcat (char*, const char*); |
| @end smallexample |
| |
| The @code{write_only} access mode applies to arguments of pointer types |
| without the @code{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 @code{write_only} access mode is the first argument to |
| the @code{strcpy} function, or the first two arguments to the @code{fgets} |
| function. |
| |
| @smallexample |
| __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*); |
| @end smallexample |
| |
| The access mode @code{none} specifies that the pointer 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 @var{size-index} argument. When the optional @var{size-index} |
| argument is omitted for an argument of @code{void*} type the actual pointer |
| agument 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 @code{__builtin_object_size}. |
| @xref{Object Size Checking}. |
| |
| Note that the @code{access} attribute merely specifies how an object |
| referenced by the pointer argument can be accessed; it does not imply that |
| an access @strong{will} happen. Also, the @code{access} attribute does not |
| imply the attribute @code{nonnull}; 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 @code{nonnull} attribute for more information and |
| caveats. |
| |
| @item alias ("@var{target}") |
| @cindex @code{alias} function attribute |
| The @code{alias} attribute causes the declaration to be emitted as an alias |
| for another symbol, which must have been previously declared with the same |
| type, and for variables, also the same size and alignment. Declaring an alias |
| with a different type than the target is undefined and may be diagnosed. As |
| an example, the following declarations: |
| |
| @smallexample |
| void __f () @{ /* @r{Do something.} */; @} |
| void f () __attribute__ ((weak, alias ("__f"))); |
| @end smallexample |
| |
| @noindent |
| define @samp{f} to be a weak alias for @samp{__f}. In C++, the mangled name |
| for the target must be used. It is an error if @samp{__f} is not defined in |
| the same translation unit. |
| |
| This attribute requires assembler and object file support, |
| and may not be available on all targets. |
| |
| @item aligned |
| @itemx aligned (@var{alignment}) |
| @cindex @code{aligned} function attribute |
| The @code{aligned} attribute specifies a minimum alignment for |
| the first instruction of the function, measured in bytes. When specified, |
| @var{alignment} must be an integer constant power of 2. Specifying no |
| @var{alignment} argument implies the ideal alignment for the target. |
| The @code{__alignof__} operator can be used to determine what that is |
| (@pxref{Alignment}). 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 @option{-falign-functions} |
| (@pxref{Optimize Options}) option for this function. |
| |
| Note that the effectiveness of @code{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 to be aligned up to a |
| certain maximum alignment. (For some linkers, the maximum supported |
| alignment may be very very small.) See your linker documentation for |
| further information. |
| |
| The @code{aligned} attribute can also be used for variables and fields |
| (@pxref{Variable Attributes}.) |
| |
| @item alloc_align (@var{position}) |
| @cindex @code{alloc_align} function attribute |
| The @code{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 @var{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, |
| |
| @smallexample |
| void* my_memalign (size_t, size_t) __attribute__ ((alloc_align (1))); |
| @end smallexample |
| |
| @noindent |
| declares that @code{my_memalign} returns memory with minimum alignment |
| given by parameter 1. |
| |
| @item alloc_size (@var{position}) |
| @itemx alloc_size (@var{position-1}, @var{position-2}) |
| @cindex @code{alloc_size} function attribute |
| The @code{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. |
| It indicates that the returned pointer points to memory whose size is |
| given by the function argument at @var{position-1}, or by the product |
| of the arguments at @var{position-1} and @var{position-2}. Meaningful |
| sizes are positive values less than @code{PTRDIFF_MAX}. GCC uses this |
| information to improve the results of @code{__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, |
| |
| @smallexample |
| void* my_calloc (size_t, size_t) __attribute__ ((alloc_size (1, 2))); |
| void* my_realloc (void*, size_t) __attribute__ ((alloc_size (2))); |
| @end smallexample |
| |
| @noindent |
| declares that @code{my_calloc} returns memory of the size given by |
| the product of parameter 1 and 2 and that @code{my_realloc} returns memory |
| of the size given by parameter 2. |
| |
| @item always_inline |
| @cindex @code{always_inline} function attribute |
| 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. |
| |
| @item artificial |
| @cindex @code{artificial} function attribute |
| This 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. |
| |
| @item assume_aligned (@var{alignment}) |
| @itemx assume_aligned (@var{alignment}, @var{offset}) |
| @cindex @code{assume_aligned} function attribute |
| The @code{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 @var{alignment}. If the attribute has two |
| arguments, the second argument is misalignment @var{offset}. Meaningful |
| values of @var{alignment} are powers of 2 greater than one. Meaningful |
| values of @var{offset} are greater than zero and less than @var{alignment}. |
| |
| For instance |
| |
| @smallexample |
| void* my_alloc1 (size_t) __attribute__((assume_aligned (16))); |
| void* my_alloc2 (size_t) __attribute__((assume_aligned (32, 8))); |
| @end smallexample |
| |
| @noindent |
| declares that @code{my_alloc1} returns 16-byte aligned pointers and |
| that @code{my_alloc2} returns a pointer whose value modulo 32 is equal |
| to 8. |
| |
| @item cold |
| @cindex @code{cold} function attribute |
| The @code{cold} attribute on functions is used to inform the compiler that |
| the function is unlikely to be executed. The function is optimized for |
| size rather than speed and on many targets it is placed into a special |
| subsection of the text section so all cold functions appear close together, |
| improving code locality of non-cold parts of program. The paths leading |
| to calls of cold functions within code are marked as unlikely by the branch |
| prediction mechanism. It is thus useful to mark functions used to handle |
| unlikely conditions, such as @code{perror}, as cold to improve optimization |
| of hot functions that do call marked functions in rare occasions. |
| |
| When profile feedback is available, via @option{-fprofile-use}, cold functions |
| are automatically detected and this attribute is ignored. |
| |
| @item const |
| @cindex @code{const} function attribute |
| @cindex functions that have no side effects |
| 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 @code{const} attribute allows GCC to avoid emitting |
| some calls in repeated invocations of the function with the same argument |
| values. |
| |
| For example, |
| |
| @smallexample |
| int square (int) __attribute__ ((const)); |
| @end smallexample |
| |
| @noindent |
| tells GCC that subsequent calls to function @code{square} with the same |
| argument value can be replaced by the result of the first call regardless |
| of the statements in between. |
| |
| The @code{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 @code{const} attribute imposes greater restrictions on a function's |
| definition than the similar @code{pure} attribute. Declaring the same |
| function with both the @code{const} and the @code{pure} attribute is |
| diagnosed. Because a const function cannot have any observable side |
| effects it does not make sense for it to return @code{void}. Declaring |
| such a function is diagnosed. |
| |
| @cindex pointer arguments |
| Note that a function that has pointer arguments and examines the data |
| pointed to must @emph{not} be declared @code{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. |
| |
| @item constructor |
| @itemx destructor |
| @itemx constructor (@var{priority}) |
| @itemx destructor (@var{priority}) |
| @cindex @code{constructor} function attribute |
| @cindex @code{destructor} function attribute |
| The @code{constructor} attribute causes the function to be called |
| automatically before execution enters @code{main ()}. Similarly, the |
| @code{destructor} attribute causes the function to be called |
| automatically after @code{main ()} completes or @code{exit ()} is |
| called. Functions with these attributes are useful for |
| initializing data that is used implicitly during the execution of |
| the program. |
| |
| On some targets the attributes also accept an integer argument to |
| specify a priority to control the order in which constructor and |
| destructor functions are run. A constructor |
| with a smaller priority number runs before a constructor with a larger |
| priority number; the opposite relationship holds for destructors. Note |
| that priorities 0-100 are reserved. So, if you have a constructor that |
| allocates a resource and a destructor that deallocates the same |
| resource, both functions typically have the same priority. The |
| priorities for constructor and destructor functions are the same as |
| those specified for namespace-scope C++ objects (@pxref{C++ Attributes}). |
| However, at present, the order in which constructors for C++ objects |
| with static storage duration and functions decorated with attribute |
| @code{constructor} are invoked is unspecified. In mixed declarations, |
| attribute @code{init_priority} can be used to impose a specific ordering. |
| |
| Using the argument forms of the @code{constructor} and @code{destructor} |
| attributes on targets where the feature is not supported is rejected with |
| an error. |
| |
| @item copy |
| @itemx copy (@var{function}) |
| @cindex @code{copy} function attribute |
| The @code{copy} attribute applies the set of attributes with which |
| @var{function} has been declared to the declaration of the function |
| 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 @code{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 @code{copy} attribute copies only syntactic and semantic attributes |
| but not attributes that affect a symbol's linkage or visibility such as |
| @code{alias}, @code{visibility}, or @code{weak}. The @code{deprecated} |
| and @code{target_clones} attribute are also not copied. |
| @xref{Common Type Attributes}. |
| @xref{Common Variable Attributes}. |
| |
| For example, the @var{StrongAlias} macro below makes use of the @code{alias} |
| and @code{copy} attributes to define an alias named @var{alloc} for function |
| @var{allocate} declared with attributes @var{alloc_size}, @var{malloc}, and |
| @var{nothrow}. Thanks to the @code{__typeof__} operator the alias has |
| the same type as the target function. As a result of the @code{copy} |
| attribute the alias also shares the same attributes as the target. |
| |
| @smallexample |
| #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); |
| @end smallexample |
| |
| @item deprecated |
| @itemx deprecated (@var{msg}) |
| @cindex @code{deprecated} function attribute |
| The @code{deprecated} attribute results in a warning if the function |
| is used anywhere in the source file. This is useful when identifying |
| functions that are expected to be removed in a future version of a |
| program. The warning also includes the location of the declaration |
| of the deprecated function, to enable users to easily find further |
| information about why the function is deprecated, or what they should |
| do instead. Note that the warnings only occurs for uses: |
| |
| @smallexample |
| int old_fn () __attribute__ ((deprecated)); |
| int old_fn (); |
| int (*fn_ptr)() = old_fn; |
| @end smallexample |
| |
| @noindent |
| results in a warning on line 3 but not line 2. The optional @var{msg} |
| argument, which must be a string, is printed in the warning if |
| present. |
| |
| The @code{deprecated} attribute can also be used for variables and |
| types (@pxref{Variable Attributes}, @pxref{Type Attributes}.) |
| |
| The message attached to the attribute is affected by the setting of |
| the @option{-fmessage-length} option. |
| |
| @item unavailable |
| @itemx unavailable (@var{msg}) |
| @cindex @code{unavailable} function attribute |
| The @code{unavailable} attribute results in an error if the function |
| is used anywhere in the source file. This is useful when identifying |
| functions that have been removed from a particular variation of an |
| interface. Other than emitting an error rather than a warning, the |
| @code{unavailable} attribute behaves in the same manner as |
| @code{deprecated}. |
| |
| The @code{unavailable} attribute can also be used for variables and |
| types (@pxref{Variable Attributes}, @pxref{Type Attributes}.) |
| |
| @item error ("@var{message}") |
| @itemx warning ("@var{message}") |
| @cindex @code{error} function attribute |
| @cindex @code{warning} function attribute |
| If the @code{error} or @code{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 @var{message} is diagnosed. |
| This is useful |
| for compile-time checking, especially together with @code{__builtin_constant_p} |
| and inline functions where checking the inline function arguments is not |
| possible through @code{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 @code{.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. |
| |
| @item externally_visible |
| @cindex @code{externally_visible} function attribute |
| This attribute, attached to a global variable or function, nullifies |
| the effect of the @option{-fwhole-program} command-line option, so the |
| object remains visible outside the current compilation unit. |
| |
| If @option{-fwhole-program} is used together with @option{-flto} and |
| @command{gold} is used as the linker plugin, |
| @code{externally_visible} attributes are automatically added to functions |
| (not variable yet due to a current @command{gold} issue) |
| that are accessed outside of LTO objects according to resolution file |
| produced by @command{gold}. |
| For other linkers that cannot generate resolution file, |
| explicit @code{externally_visible} attributes are still necessary. |
| |
| @item flatten |
| @cindex @code{flatten} function attribute |
| Generally, inlining into a function is limited. For a function marked with |
| this attribute, every call inside this function is inlined, if possible. |
| Functions declared with attribute @code{noinline} and similar are not |
| inlined. Whether the function itself is considered for inlining depends |
| on its size and the current inlining parameters. |
| |
| @item format (@var{archetype}, @var{string-index}, @var{first-to-check}) |
| @cindex @code{format} function attribute |
| @cindex functions with @code{printf}, @code{scanf}, @code{strftime} or @code{strfmon} style arguments |
| @opindex Wformat |
| The @code{format} attribute specifies that a function takes @code{printf}, |
| @code{scanf}, @code{strftime} or @code{strfmon} style arguments that |
| should be type-checked against a format string. For example, the |
| declaration: |
| |
| @smallexample |
| extern int |
| my_printf (void *my_object, const char *my_format, ...) |
| __attribute__ ((format (printf, 2, 3))); |
| @end smallexample |
| |
| @noindent |
| causes the compiler to check the arguments in calls to @code{my_printf} |
| for consistency with the @code{printf} style format string argument |
| @code{my_format}. |
| |
| The parameter @var{archetype} determines how the format string is |
| interpreted, and should be @code{printf}, @code{scanf}, @code{strftime}, |
| @code{gnu_printf}, @code{gnu_scanf}, @code{gnu_strftime} or |
| @code{strfmon}. (You can also use @code{__printf__}, |
| @code{__scanf__}, @code{__strftime__} or @code{__strfmon__}.) On |
| MinGW targets, @code{ms_printf}, @code{ms_scanf}, and |
| @code{ms_strftime} are also present. |
| @var{archetype} values such as @code{printf} refer to the formats accepted |
| by the system's C runtime library, |
| while values prefixed with @samp{gnu_} always refer |
| to the formats accepted by the GNU C Library. On Microsoft Windows |
| targets, values prefixed with @samp{ms_} refer to the formats accepted by the |
| @file{msvcrt.dll} library. |
| The parameter @var{string-index} |
| specifies which argument is the format string argument (starting |
| from 1), while @var{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 |
| @code{vprintf}), specify the third parameter as zero. In this case the |
| compiler only checks the format string for consistency. For |
| @code{strftime} formats, the third parameter is required to be zero. |
| Since non-static C++ methods have an implicit @code{this} argument, the |
| arguments of such methods should be counted from two, not one, when |
| giving values for @var{string-index} and @var{first-to-check}. |
| |
| In the example above, the format string (@code{my_format}) is the second |
| argument of the function @code{my_print}, and the arguments to check |
| start with the third argument, so the correct parameters for the format |
| attribute are 2 and 3. |
| |
| @opindex ffreestanding |
| @opindex fno-builtin |
| The @code{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 |
| @option{-ffreestanding} or @option{-fno-builtin} is used) checks formats |
| for the standard library functions @code{printf}, @code{fprintf}, |
| @code{sprintf}, @code{scanf}, @code{fscanf}, @code{sscanf}, @code{strftime}, |
| @code{vprintf}, @code{vfprintf} and @code{vsprintf} whenever such |
| warnings are requested (using @option{-Wformat}), so there is no need to |
| modify the header file @file{stdio.h}. In C99 mode, the functions |
| @code{snprintf}, @code{vsnprintf}, @code{vscanf}, @code{vfscanf} and |
| @code{vsscanf} are also checked. Except in strictly conforming C |
| standard modes, the X/Open function @code{strfmon} is also checked as |
| are @code{printf_unlocked} and @code{fprintf_unlocked}. |
| @xref{C Dialect Options,,Options Controlling C Dialect}. |
| |
| For Objective-C dialects, @code{NSString} (or @code{__NSString__}) is |
| recognized in the same context. Declarations including these format attributes |
| are parsed for correct syntax, however the result of checking of such format |
| strings is not yet defined, and is not carried out by this version of the |
| compiler. |
| |
| The target may also provide additional types of format checks. |
| @xref{Target Format Checks,,Format Checks Specific to Particular |
| Target Machines}. |
| |
| @item format_arg (@var{string-index}) |
| @cindex @code{format_arg} function attribute |
| @opindex Wformat-nonliteral |
| The @code{format_arg} attribute specifies that a function takes one or |
| more format strings for a @code{printf}, @code{scanf}, @code{strftime} or |
| @code{strfmon} style function and modifies it (for example, to translate |
| it into another language), so the result can be passed to a |
| @code{printf}, @code{scanf}, @code{strftime} or @code{strfmon} style |
| function (with the remaining arguments to the format function the same |
| as they would have been for the unmodified string). Multiple |
| @code{format_arg} attributes may be applied to the same function, each |
| designating a distinct parameter as a format string. For example, the |
| declaration: |
| |
| @smallexample |
| extern char * |
| my_dgettext (char *my_domain, const char *my_format) |
| __attribute__ ((format_arg (2))); |
| @end smallexample |
| |
| @noindent |
| causes the compiler to check the arguments in calls to a @code{printf}, |
| @code{scanf}, @code{strftime} or @code{strfmon} type function, whose |
| format string argument is a call to the @code{my_dgettext} function, for |
| consistency with the format string argument @code{my_format}. If the |
| @code{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 |
| @option{-Wformat-nonliteral} is used, but the calls could not be checked |
| without the attribute. |
| |
| In calls to a function declared with more than one @code{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 @code{ngettext} family of functions. |
| |
| The parameter @var{string-index} specifies which argument is the format |
| string argument (starting from one). Since non-static C++ methods have |
| an implicit @code{this} argument, the arguments of such methods should |
| be counted from two. |
| |
| The @code{format_arg} attribute allows you to identify your own |
| functions that modify format strings, so that GCC can check the |
| calls to @code{printf}, @code{scanf}, @code{strftime} or @code{strfmon} |
| type function whose operands are a call to one of your own function. |
| The compiler always treats @code{gettext}, @code{dgettext}, and |
| @code{dcgettext} in this manner except when strict ISO C support is |
| requested by @option{-ansi} or an appropriate @option{-std} option, or |
| @option{-ffreestanding} or @option{-fno-builtin} |
| is used. @xref{C Dialect Options,,Options |
| Controlling C Dialect}. |
| |
| For Objective-C dialects, the @code{format-arg} attribute may refer to an |
| @code{NSString} reference for compatibility with the @code{format} attribute |
| above. |
| |
| The target may also allow additional types in @code{format-arg} attributes. |
| @xref{Target Format Checks,,Format Checks Specific to Particular |
| Target Machines}. |
| |
| @item gnu_inline |
| @cindex @code{gnu_inline} function attribute |
| This attribute should be used with a function that is also declared |
| with the @code{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 @code{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 @code{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 @code{extern} nor @code{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 |
| @code{inline}. Since ISO C99 specifies a different semantics for |
| @code{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 @code{__GNUC_GNU_INLINE__} or |
| @code{__GNUC_STDC_INLINE__} are defined. @xref{Inline,,An Inline |
| Function is As Fast As a Macro}. |
| |
| In C++, this attribute does not depend on @code{extern} in any way, |
| but it still requires the @code{inline} keyword to enable its special |
| behavior. |
| |
| @item hot |
| @cindex @code{hot} function attribute |
| The @code{hot} attribute on a function is used to inform the compiler that |
| the function is a hot spot of the compiled program. The function is |
| optimized more aggressively and on many targets it is placed into a special |
| subsection of the text section so all hot functions appear close together, |
| improving locality. |
| |
| When profile feedback is available, via @option{-fprofile-use}, hot functions |
| are automatically detected and this attribute is ignored. |
| |
| @item ifunc ("@var{resolver}") |
| @cindex @code{ifunc} function attribute |
| @cindex indirect functions |
| @cindex functions that are dynamically resolved |
| The @code{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: |
| |
| @smallexample |
| void *my_memcpy (void *dst, const void *src, size_t len) |
| @{ |
| @dots{} |
| return dst; |
| @} |
| |
| static void * (*resolve_memcpy (void))(void *, const void *, size_t) |
| @{ |
| return my_memcpy; // we will just always select this routine |
| @} |
| @end smallexample |
| |
| @noindent |
| The exported header file declaring the function the user calls would |
| contain: |
| |
| @smallexample |
| extern void *memcpy (void *, const void *, size_t); |
| @end smallexample |
| |
| @noindent |
| allowing the user to call @code{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: |
| |
| @smallexample |
| void *memcpy (void *, const void *, size_t) |
| __attribute__ ((ifunc ("resolve_memcpy"))); |
| @end smallexample |
| |
| In C++, the @code{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 @code{C} should be declared to return a pointer to a non-member |
| function taking pointer to @code{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 @option{-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 @option{-Wno-pmf-conversions} option. For example: |
| |
| @smallexample |
| 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) @{ /* @r{@dots{}} */ @} |
| int S::optimized_impl (int) @{ /* @r{@dots{}} */ @} |
| |
| 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"))); |
| @end smallexample |
| |
| 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. |
| |
| @item interrupt |
| @itemx interrupt_handler |
| 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. |
| |
| @item leaf |
| @cindex @code{leaf} function attribute |
| 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 @code{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 @code{sin} function is a leaf function, but |
| @code{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 @code{leaf} attribute or mark all such static variables |
| @code{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. |
| |
| @item malloc |
| @item malloc (@var{deallocator}) |
| @item malloc (@var{deallocator}, @var{ptr-index}) |
| @cindex @code{malloc} function attribute |
| @cindex functions that behave like malloc |
| Attribute @code{malloc} indicates that a function is @code{malloc}-like, |
| i.e., that the pointer @var{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 @var{P}. In |
| addition, the 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 @code{deallocator} as a suitable deallocation function for |
| pointers returned from the @code{malloc}-like function. @var{ptr-index} |
| denotes the positional argument to which when the pointer is passed in |
| calls to @code{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 @code{malloc} |
| and @code{calloc} have this property because they return a pointer to |
| uninitialized or zeroed-out, newly obtained storage. However, functions |
| like @code{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 @var{deallocator} helps detect calls to |
| mismatched allocation and deallocation functions and diagnose them under |
| the control of options such as @option{-Wmismatched-dealloc}. It also |
| makes it possible to diagnose attempts to deallocate objects that were not |
| allocated dynamically, by @option{-Wfree-nonheap-object}. To indicate |
| that an allocation function both satisifies the nonaliasing property and |
| has a deallocator associated with it, both the plain form of the attribute |
| and the one with the @var{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 @code{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 @code{fclose} |
| a suitable deallocator for pointers returned from all functions except |
| @code{popen}, and @code{pclose} as the only suitable deallocator for |
| pointers returned from @code{popen}. The deallocator functions must |
| be declared before they can be referenced in the attribute. |
| |
| @smallexample |
| int fclose (FILE*); |
| int pclose (FILE*); |
| |
| __attribute__ ((malloc, malloc (fclose, 1))) |
| FILE* fdopen (int, const char*); |
| __attribute__ ((malloc, malloc (fclose, 1))) |
| FILE* fopen (const char*, const char*); |
| __attribute__ ((malloc, malloc (fclose, 1))) |
| FILE* fmemopen(void *, size_t, const char *); |
| __attribute__ ((malloc, malloc (pclose, 1))) |
| FILE* popen (const char*, const char*); |
| __attribute__ ((malloc, malloc (fclose, 1))) |
| FILE* tmpfile (void); |
| @end smallexample |
| |
| The warnings guarded by @option{-fanalyzer} respect allocation and |
| deallocation pairs marked with the @code{malloc}. In particular: |
| |
| @itemize @bullet |
| |
| @item |
| The analyzer will emit a @option{-Wanalyzer-mismatching-deallocation} |
| diagnostic if there is an execution path in which the result of an |
| allocation call is passed to a different deallocator. |
| |
| @item |
| The analyzer will emit a @option{-Wanalyzer-double-free} |
| diagnostic if there is an execution path in which a value is passed |
| more than once to a deallocation call. |
| |
| @item |
| The analyzer will consider the possibility that an allocation function |
| could fail and return NULL. It will emit |
| @option{-Wanalyzer-possible-null-dereference} and |
| @option{-Wanalyzer-possible-null-argument} diagnostics 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. |
| If the allocator always returns non-null, use |
| @code{__attribute__ ((returns_nonnull))} to suppress these warnings. |
| For example: |
| @smallexample |
| char *xstrdup (const char *) |
| __attribute__((malloc (free), returns_nonnull)); |
| @end smallexample |
| |
| @item |
| The analyzer will emit a @option{-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. |
| |
| @item |
| The analyzer will emit a @option{-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). |
| |
| @item |
| The analyzer will emit a @option{-Wanalyzer-free-of-non-heap} diagnostic |
| if a deallocation function is used on a global or on-stack variable. |
| |
| @end itemize |
| |
| The analyzer assumes that deallocators can gracefully handle the @code{NULL} |
| pointer. If this is not the case, the deallocator can be marked with |
| @code{__attribute__((nonnull))} so that @option{-fanalyzer} can emit |
| a @option{-Wanalyzer-possible-null-argument} diagnostic for code paths |
| in which the deallocator is called with NULL. |
| |
| @item no_icf |
| @cindex @code{no_icf} function attribute |
| This function attribute prevents a functions from being merged with another |
| semantically equivalent function. |
| |
| @item no_instrument_function |
| @cindex @code{no_instrument_function} function attribute |
| @opindex finstrument-functions |
| @opindex p |
| @opindex pg |
| If any of @option{-finstrument-functions}, @option{-p}, or @option{-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. |
| |
| @item no_profile_instrument_function |
| @cindex @code{no_profile_instrument_function} function attribute |
| The @code{no_profile_instrument_function} attribute on functions is used |
| to inform the compiler that it should not process any profile feedback based |
| optimization code instrumentation. |
| |
| @item no_reorder |
| @cindex @code{no_reorder} function attribute |
| Do not reorder functions or variables marked @code{no_reorder} |
| against each other or top level assembler statements the executable. |
| The actual order in the program will depend on the linker command |
| line. Static variables marked like this are also not removed. |
| This has a similar effect |
| as the @option{-fno-toplevel-reorder} option, but only applies to the |
| marked symbols. |
| |
| @item no_sanitize ("@var{sanitize_option}") |
| @cindex @code{no_sanitize} function attribute |
| The @code{no_sanitize} attribute on functions is used |
| to inform the compiler that it should not do sanitization of any option |
| mentioned in @var{sanitize_option}. A list of values acceptable by |
| the @option{-fsanitize} option can be provided. |
| |
| @smallexample |
| void __attribute__ ((no_sanitize ("alignment", "object-size"))) |
| f () @{ /* @r{Do something.} */; @} |
| void __attribute__ ((no_sanitize ("alignment,object-size"))) |
| g () @{ /* @r{Do something.} */; @} |
| @end smallexample |
| |
| @item no_sanitize_address |
| @itemx no_address_safety_analysis |
| @cindex @code{no_sanitize_address} function attribute |
| The @code{no_sanitize_address} attribute on functions is used |
| to inform the compiler that it should not instrument memory accesses |
| in the function when compiling with the @option{-fsanitize=address} option. |
| The @code{no_address_safety_analysis} is a deprecated alias of the |
| @code{no_sanitize_address} attribute, new code should use |
| @code{no_sanitize_address}. |
| |
| @item no_sanitize_thread |
| @cindex @code{no_sanitize_thread} function attribute |
| The @code{no_sanitize_thread} attribute on functions is used |
| to inform the compiler that it should not instrument memory accesses |
| in the function when compiling with the @option{-fsanitize=thread} option. |
| |
| @item no_sanitize_undefined |
| @cindex @code{no_sanitize_undefined} function attribute |
| The @code{no_sanitize_undefined} attribute on functions is used |
| to inform the compiler that it should not check for undefined behavior |
| in the function when compiling with the @option{-fsanitize=undefined} option. |
| |
| @item no_sanitize_coverage |
| @cindex @code{no_sanitize_coverage} function attribute |
| The @code{no_sanitize_coverage} attribute on functions is used |
| to inform the compiler that it should not do coverage-guided |
| fuzzing code instrumentation (@option{-fsanitize-coverage}). |
| |
| @item no_split_stack |
| @cindex @code{no_split_stack} function attribute |
| @opindex fsplit-stack |
| If @option{-fsplit-stack} is given, functions have a small |
| prologue which decides whether to split the stack. Functions with the |
| @code{no_split_stack} attribute do not have that prologue, and thus |
| may run with only a small amount of stack space available. |
| |
| @item no_stack_limit |
| @cindex @code{no_stack_limit} function attribute |
| This attribute locally overrides the @option{-fstack-limit-register} |
| and @option{-fstack-limit-symbol} command-line options; it has the effect |
| of disabling stack limit checking in the function it applies to. |
| |
| @item noclone |
| @cindex @code{noclone} function attribute |
| This function 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. |
| |
| @item noinline |
| @cindex @code{noinline} function attribute |
| This function attribute prevents a function from being considered for |
| inlining. |
| @c Don't enumerate the optimizations by name here; we try to be |
| @c future-compatible with this mechanism. |
| If the function does not have side effects, there are optimizations |
| other than inlining that cause function calls to be optimized away, |
| although the function call is live. To keep such calls from being |
| optimized away, put |
| @smallexample |
| asm (""); |
| @end smallexample |
| |
| @noindent |
| (@pxref{Extended Asm}) in the called function, to serve as a special |
| side effect. |
| |
| @item noipa |
| @cindex @code{noipa} function attribute |
| Disable 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 @code{noinline}, @code{noclone} and |
| @code{no_icf} attributes. However, this attribute is not equivalent |
| to a combination of other attributes, because its purpose is to suppress |
| existing and future optimizations employing interprocedural analysis, |
| including those that do not have an attribute suitable for disabling |
| them individually. This attribute is supported mainly for the purpose |
| of testing the compiler. |
| |
| @item nonnull |
| @itemx nonnull (@var{arg-index}, @dots{}) |
| @cindex @code{nonnull} function attribute |
| @cindex functions with non-null pointer arguments |
| The @code{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: |
| |
| @smallexample |
| extern void * |
| my_memcpy (void *dest, const void *src, size_t len) |
| __attribute__((nonnull (1, 2))); |
| @end smallexample |
| |
| @noindent |
| informs the compiler that, in calls to @code{my_memcpy}, arguments |
| @var{dest} and @var{src} must be non-null. |
| |
| The attribute has an effect both on functions calls and function definitions. |
| |
| For function calls: |
| @itemize @bullet |
| @item If the compiler determines that a null pointer is |
| passed in an argument slot marked as non-null, and the |
| @option{-Wnonnull} option is enabled, a warning is issued. |
| @xref{Warning Options}. |
| @item The @option{-fisolate-erroneous-paths-attribute} option can be |
| specified to have GCC transform calls with null arguments to non-null |
| functions into traps. @xref{Optimize Options}. |
| @item The compiler may also perform optimizations based on the |
| knowledge that certain function arguments cannot be null. These |
| optimizations can be disabled by the |
| @option{-fno-delete-null-pointer-checks} option. @xref{Optimize Options}. |
| @end itemize |
| |
| For function definitions: |
| @itemize @bullet |
| @item If the compiler determines that a function parameter that is |
| marked with nonnull is compared with null, and |
| @option{-Wnonnull-compare} option is enabled, a warning is issued. |
| @xref{Warning Options}. |
| @item The compiler may also perform optimizations based on the |
| knowledge that @code{nonnul} parameters cannot be null. This can |
| currently not be disabled other than by removing the nonnull |
| attribute. |
| @end itemize |
| |
| If no @var{arg-index} is given to the @code{nonnull} attribute, |
| all pointer arguments are marked as non-null. To illustrate, the |
| following declaration is equivalent to the previous example: |
| |
| @smallexample |
| extern void * |
| my_memcpy (void *dest, const void *src, size_t len) |
| __attribute__((nonnull)); |
| @end smallexample |
| |
| @item noplt |
| @cindex @code{noplt} function attribute |
| The @code{noplt} attribute is the counterpart to option @option{-fno-plt}. |
| Calls to functions marked with this attribute in position-independent code |
| do not use the PLT. |
| |
| @smallexample |
| @group |
| /* Externally defined function foo. */ |
| int foo () __attribute__ ((noplt)); |
| |
| int |
| main (/* @r{@dots{}} */) |
| @{ |
| /* @r{@dots{}} */ |
| foo (); |
| /* @r{@dots{}} */ |
| @} |
| @end group |
| @end smallexample |
| |
| The @code{noplt} attribute on function @code{foo} |
| tells the compiler to assume that |
| the function @code{foo} is externally defined and that the call to |
| @code{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. |
| |
| @item noreturn |
| @cindex @code{noreturn} function attribute |
| @cindex functions that never return |
| A few standard library functions, such as @code{abort} and @code{exit}, |
| cannot return. GCC knows this automatically. Some programs define |
| their own functions that never return. You can declare them |
| @code{noreturn} to tell the compiler this fact. For example, |
| |
| @smallexample |
| @group |
| void fatal () __attribute__ ((noreturn)); |
| |
| void |
| fatal (/* @r{@dots{}} */) |
| @{ |
| /* @r{@dots{}} */ /* @r{Print error message.} */ /* @r{@dots{}} */ |
| exit (1); |
| @} |
| @end group |
| @end smallexample |
| |
| The @code{noreturn} keyword tells the compiler to assume that |
| @code{fatal} cannot return. It can then optimize without regard to what |
| would happen if @code{fatal} ever did return. This makes slightly |
| better code. More importantly, it helps avoid spurious warnings of |
| uninitialized variables. |
| |
| The @code{noreturn} keyword does not affect the exceptional path when that |
| applies: a @code{noreturn}-marked function may still return to the caller |
| by throwing an exception or calling @code{longjmp}. |
| |
| In order to preserve backtraces, GCC will never turn calls to |
| @code{noreturn} functions into tail calls. |
| |
| Do not assume that registers saved by the calling function are |
| restored before calling the @code{noreturn} function. |
| |
| It does not make sense for a @code{noreturn} function to have a return |
| type other than @code{void}. |
| |
| @item nothrow |
| @cindex @code{nothrow} function attribute |
| The @code{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 @code{qsort} and @code{bsearch} that |
| take function pointer arguments. |
| |
| @item optimize (@var{level}, @dots{}) |
| @item optimize (@var{string}, @dots{}) |
| @cindex @code{optimize} function attribute |
| The @code{optimize} attribute is used to specify that a function is to |
| be compiled with different optimization options than specified on the |
| command line. The optimize attribute arguments of a function behave |
| behave as if appended to the command-line. |
| |
| Valid arguments are constant non-negative integers and |
| strings. Each numeric argument specifies an optimization @var{level}. |
| Each @var{string} argument consists of one or more comma-separated |
| substrings. Each substring that begins with the letter @code{O} refers |
| to an optimization option such as @option{-O0} or @option{-Os}. Other |
| substrings are taken as suffixes to the @code{-f} prefix jointly |
| forming the name of an optimization option. @xref{Optimize Options}. |
| |
| @samp{#pragma GCC optimize} can be used to set optimization options |
| for more than one function. @xref{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 (@samp{,}) within a single string. Spaces are not permitted |
| within the strings. |
| |
| Not every optimization option that starts with the @var{-f} prefix |
| specified by the attribute necessarily has an effect on the function. |
| The @code{optimize} attribute should be used for debugging purposes only. |
| It is not suitable in production code. |
| |
| @item patchable_function_entry |
| @cindex @code{patchable_function_entry} function attribute |
| @cindex extra NOP instructions at the function entry point |
| 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 @code{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 |
| @option{-fpatchable-function-entry=N,M}, generating @var{N} NOPs, with |
| the function entry point before the @var{M}th NOP instruction. |
| @var{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 @option{-fpatchable-function-entry=N,M}, then you must disable |
| instrumentation on all functions that are part of the instrumentation |
| framework with the attribute @code{patchable_function_entry (0)} |
| to prevent recursion. |
| |
| @item pure |
| @cindex @code{pure} function attribute |
| @cindex functions that have no side effects |
| |
| 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 @code{pure} attribute allows GCC to avoid emitting some calls in repeated |
| invocations of the function with the same argument values. |
| |
| The @code{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 @code{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, |
| |
| @smallexample |
| int hash (char *) __attribute__ ((pure)); |
| @end smallexample |
| |
| @noindent |
| tells GCC that subsequent calls to the function @code{hash} with the same |
| string can be replaced by the result of the first call provided the state |
| of the program observable by @code{hash}, including the contents of the array |
| itself, does not change in between. Even though @code{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 @code{this} pointer in C++ |
| non-static member functions. |
| |
| Some common examples of pure functions are @code{strlen} or @code{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 @code{feof} function in |
| a multithreading environment). |
| |
| The @code{pure} attribute imposes similar but looser restrictions on |
| a function's definition than the @code{const} attribute: @code{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 @code{pure} and the @code{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 @code{void}. |
| Declaring such a function is diagnosed. |
| |
| @item returns_nonnull |
| @cindex @code{returns_nonnull} function attribute |
| The @code{returns_nonnull} attribute specifies that the function |
| return value should be a non-null pointer. For instance, the declaration: |
| |
| @smallexample |
| extern void * |
| mymalloc (size_t len) __attribute__((returns_nonnull)); |
| @end smallexample |
| |
| @noindent |
| lets the compiler optimize callers based on the knowledge |
| that the return value will never be null. |
| |
| @item returns_twice |
| @cindex @code{returns_twice} function attribute |
| @cindex functions that return more than once |
| The @code{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 @code{setjmp} and @code{vfork}. |
| The @code{longjmp}-like counterpart of such function, if any, might need |
| to be marked with the @code{noreturn} attribute. |
| |
| @item section ("@var{section-name}") |
| @cindex @code{section} function attribute |
| @cindex functions in arbitrary sections |
| Normally, the compiler places the code it generates in the @code{text} section. |
| Sometimes, however, you need additional sections, or you need certain |
| particular functions to appear in special sections. The @code{section} |
| attribute specifies that a function lives in a particular section. |
| For example, the declaration: |
| |
| @smallexample |
| extern void foobar (void) __attribute__ ((section ("bar"))); |
| @end smallexample |
| |
| @noindent |
| puts the function @code{foobar} in the @code{bar} section. |
| |
| Some file formats do not support arbitrary sections so the @code{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. |
| |
| @item sentinel |
| @itemx sentinel (@var{position}) |
| @cindex @code{sentinel} function attribute |
| This function attribute indicates that an argument in a call to the function |
| is expected to be an explicit @code{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 @var{position} argument |
| is specified to the attribute, the sentinel must be located at |
| @var{position} counting backwards from the end of the argument list. |
| |
| @smallexample |
| __attribute__ ((sentinel)) |
| is equivalent to |
| __attribute__ ((sentinel(0))) |
| @end smallexample |
| |
| The attribute is automatically set with a position of 0 for the built-in |
| functions @code{execl} and @code{execlp}. The built-in function |
| @code{execle} has the attribute set with a position of 1. |
| |
| A valid @code{NULL} in this context is defined as zero with any object |
| pointer type. If your system defines the @code{NULL} macro with |
| an integer type then you need to add an explicit cast. During |
| installation GCC replaces the system @code{<stddef.h>} header with |
| a copy that redefines NULL appropriately. |
| |
| The warnings for missing or incorrect sentinels are enabled with |
| @option{-Wformat}. |
| |
| @item simd |
| @itemx simd("@var{mask}") |
| @cindex @code{simd} function attribute |
| This attribute 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 |
| @w{@uref{https://sourceware.org/glibc/wiki/libmvec?action=AttachFile&do=view&target=VectorABI.txt,here}}. |
| |
| The optional argument @var{mask} may have the value |
| @code{notinbranch} or @code{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 @code{#pragma omp declare simd} is |
| present on a declaration and the @option{-fopenmp} or @option{-fopenmp-simd} |
| switch is specified, then the attribute is ignored. |
| |
| @item stack_protect |
| @cindex @code{stack_protect} function attribute |
| This attribute adds stack protection code to the function if |
| flags @option{-fstack-protector}, @option{-fstack-protector-strong} |
| or @option{-fstack-protector-explicit} are set. |
| |
| @item no_stack_protector |
| @cindex @code{no_stack_protector} function attribute |
| This attribute prevents stack protection code for the function. |
| |
| @item target (@var{string}, @dots{}) |
| @cindex @code{target} function attribute |
| Multiple target back ends implement the @code{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 @code{-m} prefix jointly forming the name of a machine-dependent |
| option. @xref{Submodel Options,,Machine-Dependent Options}. |
| |
| The @code{target} attribute can be used for instance to have a function |
| compiled with a different ISA (instruction set architecture) than the |
| default. @samp{#pragma GCC target} can be used to specify target-specific |
| options for more than one function. @xref{Function Specific Option Pragmas}, |
| for details about the pragma. |
| |
| For instance, on an x86, you could declare one function with the |
| @code{target("sse4.1,arch=core2")} attribute and another with |
| @code{target("sse4a,arch=amdfam10")}. This is equivalent to |
| compiling the first function with @option{-msse4.1} and |
| @option{-march=core2} options, and the second function with |
| @option{-msse4a} and @option{-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 |
| @code{cpuid} on x86 to determine what feature bits and architecture |
| family are used). |
| |
| @smallexample |
| int core2_func (void) __attribute__ ((__target__ ("arch=core2"))); |
| int sse3_func (void) __attribute__ ((__target__ ("sse3"))); |
| @end smallexample |
| |
| Providing multiple strings as arguments separated by commas to specify |
| multiple options is equivalent to separating the option suffixes with |
| a comma (@samp{,}) within a single string. Spaces are not permitted |
| within the strings. |
| |
| The options supported are specific to each target; refer to @ref{x86 |
| Function Attributes}, @ref{PowerPC Function Attributes}, |
| @ref{ARM Function Attributes}, @ref{AArch64 Function Attributes}, |
| @ref{Nios II Function Attributes}, and @ref{S/390 Function Attributes} |
| for details. |
| |
| @item symver ("@var{name2}@@@var{nodename}") |
| @cindex @code{symver} function attribute |
| On ELF targets this attribute creates a symbol version. The @var{name2} part |
| of the parameter is the actual name of the symbol by which it will be |
| externally referenced. The @code{nodename} portion should be the name of a |
| node specified in the version script supplied to the linker when building a |
| shared library. Versioned symbol must be defined and must be exported with |
| default visibility. |
| |
| @smallexample |
| __attribute__ ((__symver__ ("foo@@VERS_1"))) int |
| foo_v1 (void) |
| @{ |
| @} |
| @end smallexample |
| |
| Will produce a @code{.symver foo_v1, foo@@VERS_1} directive in the assembler |
| output. |
| |
| One can also define multiple version for a given symbol |
| (starting from binutils 2.35). |
| |
| @smallexample |
| __attribute__ ((__symver__ ("foo@@VERS_2"), __symver__ ("foo@@VERS_3"))) |
| int symver_foo_v1 (void) |
| @{ |
| @} |
| @end smallexample |
| |
| This example creates a symbol name @code{symver_foo_v1} |
| which will be version @code{VERS_2} and @code{VERS_3} of @code{foo}. |
| |
| If you have an older release of binutils, then symbol alias needs to |
| be used: |
| |
| @smallexample |
| __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); |
| @end smallexample |
| |
| Finally if the parameter is @code{"@var{name2}@@@@@var{nodename}"} then in |
| addition to creating a symbol version (as if |
| @code{"@var{name2}@@@var{nodename}"} was used) the version will be also used |
| to resolve @var{name2} by the linker. |
| |
| @item tainted_args |
| @cindex @code{tainted_args} function attribute |
| The @code{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 will be treated as being called with tainted |
| arguments. |
| |
| The analyzer will pay particular attention to such functions when both |
| @option{-fanalyzer} and @option{-fanalyzer-checker=taint} are supplied, |
| potentially issuing warnings guarded by |
| @option{-Wanalyzer-tainted-allocation-size}, |
| @option{-Wanalyzer-tainted-array-index}, |
| @option{-Wanalyzer-tainted-divisor}, |
| @option{-Wanalyzer-tainted-offset}, |
| and @option{-Wanalyzer-tainted-size}. |
| |
| @item target_clones (@var{options}) |
| @cindex @code{target_clones} function attribute |
| The @code{target_clones} attribute is used to specify that a function |
| be cloned into multiple versions compiled with different target options |
| than specified on the command line. The supported options and restrictions |
| are the same as for @code{target} attribute. |
| |
| For instance, on an x86, you could compile a function with |
| @code{target_clones("sse4.1,avx")}. GCC creates two function clones, |
| one compiled with @option{-msse4.1} and another with @option{-mavx}. |
| |
| On a PowerPC, you can compile a function with |
| @code{target_clones("cpu=power9,default")}. GCC will create two |
| function clones, one compiled with @option{-mcpu=power9} and another |
| with the default options. GCC must be configured to use GLIBC 2.23 or |
| newer in order to use the @code{target_clones} attribute. |
| |
| It also creates a resolver function (see |
| the @code{ifunc} attribute above) that dynamically selects a clone |
| suitable for current architecture. The resolver is created only if there |
| is a usage of a function with @code{target_clones} attribute. |
| |
| Note that any subsequent call of a function without @code{target_clone} |
| from a @code{target_clone} caller will not lead to copying |
| (target clone) of the called function. |
| If you want to enforce such behaviour, |
| we recommend declaring the calling function with the @code{flatten} attribute? |
| |
| @item unused |
| @cindex @code{unused} function attribute |
| This attribute, attached to a function, means that the function is meant |
| to be possibly unused. GCC does not produce a warning for this |
| function. |
| |
| @item used |
| @cindex @code{used} function attribute |
| This attribute, attached to a function, 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. |
| |
| @item retain |
| @cindex @code{retain} function attribute |
| For ELF targets that support the GNU or FreeBSD OSABIs, this attribute |
| will save the function from linker garbage collection. To support |
| this behavior, functions that have not been placed in specific sections |
| (e.g. by the @code{section} attribute, or the @code{-ffunction-sections} |
| option), will be placed in new, unique sections. |
| |
| This additional functionality requires Binutils version 2.36 or later. |
| |
| @item visibility ("@var{visibility_type}") |
| @cindex @code{visibility} function attribute |
| This attribute affects the linkage of the declaration to which it is attached. |
| It can be applied to variables (@pxref{Common Variable Attributes}) and types |
| (@pxref{Common Type Attributes}) as well as functions. |
| |
| There are four supported @var{visibility_type} values: default, |
| hidden, protected or internal visibility. |
| |
| @smallexample |
| void __attribute__ ((visibility ("protected"))) |
| f () @{ /* @r{Do something.} */; @} |
| int i __attribute__ ((visibility ("hidden"))); |
| @end smallexample |
| |
| The possible values of @var{visibility_type} correspond to the |
| visibility settings in the ELF gABI. |
| |
| @table @code |
| @c keep this list of visibilities in alphabetical order. |
| |
| @item 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. |
| |
| @item 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. |
| |
| @item 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 |
| @emph{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. |
| |
| @item 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. |
| |
| @end table |
| |
| All visibilities are supported on many, but not all, ELF targets |
| (supported when the assembler supports the @samp{.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. |
| |
| @smallexample |
| namespace nspace1 __attribute__ ((visibility ("protected"))) |
| @{ /* @r{Do something.} */; @} |
| @end smallexample |
| |
| This attribute applies only to the particular namespace body, not to |
| other definitions of the same namespace; it is equivalent to using |
| @samp{#pragma GCC visibility} before and after the namespace |
| definition (@pxref{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. |
| |
| @item warn_unused_result |
| @cindex @code{warn_unused_result} function attribute |
| The @code{warn_unused_result} attribute causes a warning to be emitted |
| if a caller of the function with this attribute d
|