flow and rounding behaviors are not implemented. Fixed-point types are supported by the DWARF2 debug information format.  File: gcc.info, Node: Zero Length, Next: Variable Length, Prev: Fixed-Point, Up: C Extensions 5.14 Arrays of Length Zero ========================== Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure which is really a header for a variable-length object: struct line { int length; char contents[0]; }; struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length); thisline->length = this_length; In ISO C90, you would have to give `contents' a length of 1, which means either you waste space or complicate the argument to `malloc'. In ISO C99, you would use a "flexible array member", which is slightly different in syntax and semantics: * Flexible array members are written as `contents[]' without the `0'. * Flexible array members have incomplete type, and so the `sizeof' operator may not be applied. As a quirk of the original implementation of zero-length arrays, `sizeof' evaluates to zero. * Flexible array members may only appear as the last member of a `struct' that is otherwise non-empty. * 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.) GCC versions before 3.0 allowed zero-length arrays to be statically initialized, as if they were flexible arrays. In addition to those cases that were useful, it also allowed initializations in situations that would corrupt later data. Non-empty initialization of zero-length arrays is now 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. Instead 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. I.e. in the following, `f1' is constructed as if it were declared like `f2'. struct f1 { int x; int y[]; } f1 = { 1, { 2, 3, 4 } }; struct f2 { struct f1 f1; int data[3]; } f2 = { { 1 }, { 2, 3, 4 } }; The convenience of this extension is that `f1' has the desired type, eliminating the need to consistently refer to `f2.f1'. This has symmetry with normal static arrays, in that an array of unknown size is also written with `[]'. 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: struct foo { int x; int y[]; }; struct bar { struct foo z; }; struct foo a = { 1, { 2, 3, 4 } }; // Valid. struct bar b = { { 1, { 2, 3, 4 } } }; // Invalid. struct bar c = { { 1, { } } }; // Valid. struct foo d[1] = { { 1 { 2, 3, 4 } } }; // Invalid.  File: gcc.info, Node: Empty Structures, Next: Variadic Macros, Prev: Variable Length, Up: C Extensions 5.15 Structures With No Members =============================== GCC permits a C structure to have no members: struct empty { }; The structure will have size zero. In C++, empty structures are part of the language. G++ treats empty structures as if they had a single member of type `char'.  File: gcc.info, Node: Variable Length, Next: Empty Structures, Prev: Zero Length, Up: C Extensions 5.16 Arrays of Variable Length ============================== Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C89 mode and in C++. (However, GCC's implementation of variable-length arrays does not yet conform in detail to the ISO C99 standard.) 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 brace-level is exited. For example: 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); } 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. You can use the function `alloca' to get an effect much like variable-length arrays. The function `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 `alloca' exists until the containing _function_ returns. The space for a variable-length array is deallocated as soon as the array name's scope ends. (If you use both variable-length arrays and `alloca' in the same function, deallocation of a variable-length array will also deallocate anything more recently allocated with `alloca'.) You can also use variable-length arrays as arguments to functions: struct entry tester (int len, char data[len][len]) { /* ... */ } 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 `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. struct entry tester (int len; char data[len][len], int len) { /* ... */ } The `int len' before the semicolon is a "parameter forward declaration", and it serves the purpose of making the name `len' known when the declaration of `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.  File: gcc.info, Node: Variadic Macros, Next: Escaped Newlines, Prev: Empty Structures, Up: C Extensions 5.17 Macros with a Variable Number of Arguments. ================================================ 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: #define debug(format, ...) fprintf (stderr, format, __VA_ARGS__) Here `...' is a "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 `__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: #define debug(format, args...) fprintf (stderr, format, args) 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: debug ("A message") 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, `##'. If instead you write #define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__) and if the variable arguments are omitted or empty, the `##' 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.  File: gcc.info, Node: Escaped Newlines, Next: Subscripting, Prev: Variadic Macros, Up: C Extensions 5.18 Slightly Looser Rules for Escaped Newlines =============================================== Recently, the preprocessor has relaxed its treatment of escaped newlines. Previously, the newline had to immediately follow a backslash. The current 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 _not_ treated as whitespace for the purposes of this relaxation, since they have not yet been replaced with spaces.  File: gcc.info, Node: Subscripting, Next: Pointer Arith, Prev: Escaped Newlines, Up: C Extensions 5.19 Non-Lvalue Arrays May Have Subscripts ========================================== 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 `&' operator may not be applied to them. As an extension, GCC allows such arrays to be subscripted in C89 mode, though otherwise they do not decay to pointers outside C99 mode. For example, this is valid in GNU C though not valid in C89: struct foo {int a[4];}; struct foo f(); bar (int index) { return f().a[index]; }  File: gcc.info, Node: Pointer Arith, Next: Initializers, Prev: Subscripting, Up: C Extensions 5.20 Arithmetic on `void'- and Function-Pointers ================================================ In GNU C, addition and subtraction operations are supported on pointers to `void' and on pointers to functions. This is done by treating the size of a `void' or of a function as 1. A consequence of this is that `sizeof' is also allowed on `void' and on function types, and returns 1. The option `-Wpointer-arith' requests a warning if these extensions are used.  File: gcc.info, Node: Initializers, Next: Compound Literals, Prev: Pointer Arith, Up: C Extensions 5.21 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: foo (float f, float g) { float beat_freqs[2] = { f-g, f+g }; /* ... */ }  File: gcc.info, Node: Compound Literals, Next: Designated Inits, Prev: Initializers, Up: C Extensions 5.22 Compound Literals ====================== ISO C99 supports compound literals. A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer; it is an lvalue. As an extension, GCC supports compound literals in C89 mode and in C++. Usually, the specified type is a structure. Assume that `struct foo' and `structure' are declared as shown: struct foo {int a; char b[2];} structure; Here is an example of constructing a `struct foo' with a compound literal: structure = ((struct foo) {x + y, 'a', 0}); This is equivalent to writing the following: { struct foo temp = {x + y, 'a', 0}; structure = temp; } You can also construct an array. 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: char **foo = (char *[]) { "x", "y", "z" }; Compound literals for scalar types and union types are is also allowed, but then the compound literal is equivalent to a cast. 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 was initialized only with the bracket enclosed list if the types of the compound literal and the object match. The initializer list of the compound literal must be constant. If the object being initialized has array type of unknown size, the size is determined by compound literal size. static struct foo x = (struct foo) {1, 'a', 'b'}; static int y[] = (int []) {1, 2, 3}; static int z[] = (int [3]) {1}; The above lines are equivalent to the following: static struct foo x = {1, 'a', 'b'}; static int y[] = {1, 2, 3}; static int z[] = {1, 0, 0};  File: gcc.info, Node: Designated Inits, Next: Cast to Union, Prev: Compound Literals, Up: C Extensions 5.23 Designated Initializers ============================ Standard C89 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 C89 mode as well. This extension is not implemented in GNU C++. To specify an array index, write `[INDEX] =' before the element value. For example, int a[6] = { [4] = 29, [2] = 15 }; is equivalent to int a[6] = { 0, 0, 15, 0, 29, 0 }; The index values must be constant expressions, even if the array being initialized is automatic. An alternative syntax for this which has been obsolete since GCC 2.5 but GCC still accepts is to write `[INDEX]' before the element value, with no `='. To initialize a range of elements to the same value, write `[FIRST ... LAST] = VALUE'. This is a GNU extension. For example, int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 }; If the value in it has side-effects, the side-effects will happen only once, not for each initialized field by the range initializer. 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 `.FIELDNAME =' before the element value. For example, given the following structure, struct point { int x, y; }; the following initialization struct point p = { .y = yvalue, .x = xvalue }; is equivalent to struct point p = { xvalue, yvalue }; Another syntax which has the same meaning, obsolete since GCC 2.5, is `FIELDNAME:', as shown here: struct point p = { y: yvalue, x: xvalue }; The `[INDEX]' or `.FIELDNAME' is known as a "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, union foo { int i; double d; }; union foo f = { .d = 4 }; will convert 4 to a `double' to store it in the union using the second element. By contrast, casting 4 to type `union foo' would store it into the union as the integer `i', since it is an integer. (*Note 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, int a[6] = { [1] = v1, v2, [4] = v4 }; is equivalent to int a[6] = { 0, v1, v2, 0, v4, 0 }; Labeling the elements of an array initializer is especially useful when the indices are characters or belong to an `enum' type. For example: int whitespace[256] = { [' '] = 1, ['\t'] = 1, ['\h'] = 1, ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 }; You can also write a series of `.FIELDNAME' and `[INDEX]' designators before an `=' 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 `struct point' declaration above: struct point ptarray[10] = { [2].y = yv2, [2].x = xv2, [0].x = xv0 }; If the same field is initialized multiple times, it will have value from the last initialization. If any such overridden initialization has side-effect, it is unspecified whether the side-effect happens or not. Currently, GCC will discard them and issue a warning.  File: gcc.info, Node: Case Ranges, Next: Mixed Declarations, Prev: Cast to Union, Up: C Extensions 5.24 Case Ranges ================ You can specify a range of consecutive values in a single `case' label, like this: case LOW ... HIGH: This has the same effect as the proper number of individual `case' labels, one for each integer value from LOW to HIGH, inclusive. This feature is especially useful for ranges of ASCII character codes: case 'A' ... 'Z': *Be careful:* Write spaces around the `...', for otherwise it may be parsed wrong when you use it with integer values. For example, write this: case 1 ... 5: rather than this: case 1...5:  File: gcc.info, Node: Cast to Union, Next: Case Ranges, Prev: Designated Inits, Up: C Extensions 5.25 Cast to a Union Type ========================= A cast to union type is similar to other casts, except that the type specified is a union type. You can specify the type either with `union TAG' or with a typedef name. A cast to union is actually a constructor though, not a cast, and hence does not yield an lvalue like normal casts. (*Note Compound Literals::.) The types that may be cast to the union type are those of the members of the union. Thus, given the following union and variables: union foo { int i; double d; }; int x; double y; both `x' and `y' can be cast to type `union foo'. 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: union foo u; /* ... */ u = (union foo) x == u.i = x u = (union foo) y == u.d = y You can also use the union cast as a function argument: void hack (union foo); /* ... */ hack ((union foo) x);  File: gcc.info, Node: Mixed Declarations, Next: Function Attributes, Prev: Case Ranges, Up: C Extensions 5.26 Mixed Declarations and Code ================================ ISO C99 and ISO C++ allow declarations and code to be freely mixed within compound statements. As an extension, GCC also allows this in C89 mode. For example, you could do: int i; /* ... */ i++; int j = i + 2; Each identifier is visible from where it is declared until the end of the enclosing block.  File: gcc.info, Node: Function Attributes, Next: Attribute Syntax, Prev: Mixed Declarations, Up: C Extensions 5.27 Declaring Attributes of Functions ====================================== In GNU C, you declare certain things about functions called in your program which help the compiler optimize function calls and check your code more carefully. The keyword `__attribute__' allows you to specify special attributes when making a declaration. This keyword is followed by an attribute specification inside double parentheses. The following attributes are currently defined for functions on all targets: `aligned', `alloc_size', `noreturn', `returns_twice', `noinline', `always_inline', `flatten', `pure', `const', `nothrow', `sentinel', `format', `format_arg', `no_instrument_function', `section', `constructor', `destructor', `used', `unused', `deprecated', `weak', `malloc', `alias', `warn_unused_result', `nonnull', `gnu_inline', `externally_visible', `hot', `cold', `artificial', `error' and `warning'. Several other attributes are defined for functions on particular target systems. Other attributes, including `section' are supported for variables declarations (*note Variable Attributes::) and for types (*note Type Attributes::). You may also specify attributes with `__' preceding and following each keyword. This allows you to use them in header files without being concerned about a possible macro of the same name. For example, you may use `__noreturn__' instead of `noreturn'. *Note Attribute Syntax::, for details of the exact syntax for using attributes. `alias ("TARGET")' The `alias' attribute causes the declaration to be emitted as an alias for another symbol, which must be specified. For instance, void __f () { /* Do something. */; } void f () __attribute__ ((weak, alias ("__f"))); defines `f' to be a weak alias for `__f'. In C++, the mangled name for the target must be used. It is an error if `__f' is not defined in the same translation unit. Not all target machines support this attribute. `aligned (ALIGNMENT)' This attribute specifies a minimum alignment for the function, measured in bytes. You cannot use this attribute to decrease the alignment of a function, only to increase it. However, when you explicitly specify a function alignment this will override the effect of the `-falign-functions' (*note Optimize Options::) option for this function. Note that the effectiveness of `aligned' attributes may be limited by inherent limitations in your linker. On many systems, the linker is only able to arrange for functions to be aligned up to a certain maximum alignment. (For some linkers, the maximum supported alignment may be very very small.) See your linker documentation for further information. The `aligned' attribute can also be used for variables and fields (*note Variable Attributes::.) `alloc_size' The `alloc_size' attribute is used to tell the compiler that the function return value points to memory, where the size is given by one or two of the functions parameters. GCC uses this information to improve the correctness of `__builtin_object_size'. The function parameter(s) denoting the allocated size are specified by one or two integer arguments supplied to the attribute. The allocated size is either the value of the single function argument specified or the product of the two function arguments specified. Argument numbering starts at one. For instance, void* my_calloc(size_t, size_t) __attribute__((alloc_size(1,2))) void my_realloc(void* size_t) __attribute__((alloc_size(2))) declares that my_calloc will return memory of the size given by the product of parameter 1 and 2 and that my_realloc will return memory of the size given by parameter 2. `always_inline' Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level was specified. `gnu_inline' This attribute should be used with a function which is also declared with the `inline' keyword. It directs GCC to treat the function as if it were defined in gnu89 mode even when compiling in C99 or gnu99 mode. If the function is declared `extern', then this definition of the function is used only for inlining. In no case is the function compiled as a standalone function, not even if you take its address explicitly. Such an address becomes an external reference, as if you had only declared the function, and had not defined it. This has almost the effect of a macro. The way to use this is to put a function definition in a header file with this attribute, and put another copy of the function, without `extern', in a library file. The definition in the header file will cause most calls to the function to be inlined. If any uses of the function remain, they will refer to the single copy in the library. Note that the two definitions of the functions need not be precisely the same, although if they do not have the same effect your program may behave oddly. In C, if the function is neither `extern' nor `static', then the function is compiled as a standalone function, as well as being inlined where possible. This is how GCC traditionally handled functions declared `inline'. Since ISO C99 specifies a different semantics for `inline', this function attribute is provided as a transition measure and as a useful feature in its own right. This attribute is available in GCC 4.1.3 and later. It is available if either of the preprocessor macros `__GNUC_GNU_INLINE__' or `__GNUC_STDC_INLINE__' are defined. *Note An Inline Function is As Fast As a Macro: Inline. In C++, this attribute does not depend on `extern' in any way, but it still requires the `inline' keyword to enable its special behavior. `artificial' This attribute is useful for small inline wrappers which if possible should appear during debugging as a unit, depending on the debug info format it will either mean marking the function as artificial or using the caller location for all instructions within the inlined body. `flatten' Generally, inlining into a function is limited. For a function marked with this attribute, every call inside this function will be inlined, if possible. Whether the function itself is considered for inlining depends on its size and the current inlining parameters. The `flatten' attribute only works reliably in unit-at-a-time mode. `error ("MESSAGE")' If this 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 which will include MESSAGE will be diagnosed. This is useful for compile time checking, especially together with `__builtin_constant_p' and inline functions where checking the inline function arguments is not possible through `extern char [(condition) ? 1 : -1];' tricks. While it is possible to leave the function undefined and thus invoke a link failure, when using this attribute the problem will be diagnosed earlier and with exact location of the call even in presence of inline functions or when not emitting debugging information. `warning ("MESSAGE")' If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, a warning which will include MESSAGE will be diagnosed. This is useful for compile time checking, especially together with `__builtin_constant_p' and inline functions. While it is possible to define the function with a message in `.gnu.warning*' section, when using this attribute the problem will be diagnosed earlier and with exact location of the call even in presence of inline functions or when not emitting debugging information. `cdecl' On the Intel 386, the `cdecl' attribute causes the compiler to assume that the calling function will pop off the stack space used to pass arguments. This is useful to override the effects of the `-mrtd' switch. `const' Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the `pure' attribute below, since function is not allowed to read global memory. Note that a function that has pointer arguments and examines the data pointed to must _not_ be declared `const'. Likewise, a function that calls a non-`const' function usually must not be `const'. It does not make sense for a `const' function to return `void'. The attribute `const' is not implemented in GCC versions earlier than 2.5. An alternative way to declare that a function has no side effects, which works in the current version and in some older versions, is as follows: typedef int intfn (); extern const intfn square; This approach does not work in GNU C++ from 2.6.0 on, since the language specifies that the `const' must be attached to the return value. `constructor' `destructor' `constructor (PRIORITY)' `destructor (PRIORITY)' The `constructor' attribute causes the function to be called automatically before execution enters `main ()'. Similarly, the `destructor' attribute causes the function to be called automatically after `main ()' has completed or `exit ()' has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program. You may provide an optional integer priority to control the order in which constructor and destructor functions are run. A constructor with a smaller priority number runs before a constructor with a larger priority number; the opposite relationship holds for destructors. So, if you have a constructor that allocates a resource and a destructor that deallocates the same resource, both functions typically have the same priority. The priorities for constructor and destructor functions are the same as those specified for namespace-scope C++ objects (*note C++ Attributes::). These attributes are not currently implemented for Objective-C. `deprecated' The `deprecated' attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead. Note that the warnings only occurs for uses: int old_fn () __attribute__ ((deprecated)); int old_fn (); int (*fn_ptr)() = old_fn; results in a warning on line 3 but not line 2. The `deprecated' attribute can also be used for variables and types (*note Variable Attributes::, *note Type Attributes::.) `dllexport' On Microsoft Windows targets and Symbian OS targets the `dllexport' attribute causes the compiler to provide a global pointer to a pointer in a DLL, so that it can be referenced with the `dllimport' attribute. On Microsoft Windows targets, the pointer name is formed by combining `_imp__' and the function or variable name. You can use `__declspec(dllexport)' as a synonym for `__attribute__ ((dllexport))' for compatibility with other compilers. On systems that support the `visibility' attribute, this attribute also implies "default" visibility. It is an error to explicitly specify any other visibility. Currently, the `dllexport' attribute is ignored for inlined functions, unless the `-fkeep-inline-functions' flag has been used. The attribute is also ignored for undefined symbols. When applied to C++ classes, the attribute marks defined non-inlined member functions and static data members as exports. Static consts initialized in-class are not marked unless they are also defined out-of-class. For Microsoft Windows targets there are alternative methods for including the symbol in the DLL's export table such as using a `.def' file with an `EXPORTS' section or, with GNU ld, using the `--export-all' linker flag. `dllimport' On Microsoft Windows and Symbian OS targets, the `dllimport' attribute causes the compiler to reference a function or variable via a global pointer to a pointer that is set up by the DLL exporting the symbol. The attribute implies `extern'. On Microsoft Windows targets, the pointer name is formed by combining `_imp__' and the function or variable name. You can use `__declspec(dllimport)' as a synonym for `__attribute__ ((dllimport))' for compatibility with other compilers. On systems that support the `visibility' attribute, this attribute also implies "default" visibility. It is an error to explicitly specify any other visibility. Currently, the attribute is ignored for inlined functions. If the attribute is applied to a symbol _definition_, an error is reported. If a symbol previously declared `dllimport' is later defined, the attribute is ignored in subsequent references, and a warning is emitted. The attribute is also overridden by a subsequent declaration as `dllexport'. When applied to C++ classes, the attribute marks non-inlined member functions and static data members as imports. However, the attribute is ignored for virtual methods to allow creation of vtables using thunks. On the SH Symbian OS target the `dllimport' attribute also has another affect--it can cause the vtable and run-time type information for a class to be exported. This happens when the class has a dllimport'ed constructor or a non-inline, non-pure virtual function and, for either of those two conditions, the class also has a inline constructor or destructor and has a key function that is defined in the current translation unit. For Microsoft Windows based targets the use of the `dllimport' attribute on functions is not necessary, but provides a small performance benefit by eliminating a thunk in the DLL. The use of the `dllimport' attribute on imported variables was required on older versions of the GNU linker, but can now be avoided by passing the `--enable-auto-import' switch to the GNU linker. As with functions, using the attribute for a variable eliminates a thunk in the DLL. One drawback to using this attribute is that a pointer to a _variable_ marked as `dllimport' cannot be used as a constant address. However, a pointer to a _function_ with the `dllimport' attribute can be used as a constant initializer; in this case, the address of a stub function in the import lib is referenced. On Microsoft Windows targets, the attribute can be disabled for functions by setting the `-mnop-fun-dllimport' flag. `eightbit_data' Use this attribute on the H8/300, H8/300H, and H8S to indicate that the specified variable should be placed into the eight bit data section. The compiler will generate more efficient code for certain operations on data in the eight bit data area. Note the eight bit data area is limited to 256 bytes of data. You must use GAS and GLD from GNU binutils version 2.7 or later for this attribute to work correctly. `exception_handler' Use this attribute on the Blackfin to indicate that the specified function is an exception handler. The compiler will generate function entry and exit sequences suitable for use in an exception handler when this attribute is present. `far' On 68HC11 and 68HC12 the `far' attribute causes the compiler to use a calling convention that takes care of switching memory banks when entering and leaving a function. This calling convention is also the default when using the `-mlong-calls' option. On 68HC12 the compiler will use the `call' and `rtc' instructions to call and return from a function. On 68HC11 the compiler will generate a sequence of instructions to invoke a board-specific routine to switch the memory bank and call the real function. The board-specific routine simulates a `call'. At the end of a function, it will jump to a board-specific routine instead of using `rts'. The board-specific return routine simulates the `rtc'. `fastcall' On the Intel 386, the `fastcall' attribute causes the compiler to pass the first argument (if of integral type) in the register ECX and the second argument (if of integral type) in the register EDX. Subsequent and other typed arguments are passed on the stack. The called function will pop the arguments off the stack. If the number of arguments is variable all arguments are pushed on the stack. `format (ARCHETYPE, STRING-INDEX, FIRST-TO-CHECK)' The `format' attribute specifies that a function takes `printf', `scanf', `strftime' or `strfmon' style arguments which should be type-checked against a format string. For example, the declaration: extern int my_printf (void *my_object, const char *my_format, ...) __attribute__ ((format (printf, 2, 3))); causes the compiler to check the arguments in calls to `my_printf' for consistency with the `printf' style format string argument `my_format'. The parameter ARCHETYPE determines how the format string is interpreted, and should be `printf', `scanf', `strftime' or `strfmon'. (You can also use `__printf__', `__scanf__', `__strftime__' or `__strfmon__'.) The parameter STRING-INDEX specifies which argument is the format string argument (starting from 1), while FIRST-TO-CHECK is the number of the first argument to check against the format string. For functions where the arguments are not available to be checked (such as `vprintf'), specify the third parameter as zero. In this case the compiler only checks the format string for consistency. For `strftime' formats, the third parameter is required to be zero. Since non-static C++ methods have an implicit `this' argument, the arguments of such methods should be counted from two, not one, when giving values for STRING-INDEX and FIRST-TO-CHECK. In the example above, the format string (`my_format') is the second argument of the function `my_print', and the arguments to check start with the third argument, so the correct parameters for the format attribute are 2 and 3. The `format' attribute allows you to identify your own functions which take format strings as arguments, so that GCC can check the calls to these functions for errors. The compiler always (unless `-ffreestanding' or `-fno-builtin' is used) checks formats for the standard library functions `printf', `fprintf', `sprintf', `scanf', `fscanf', `sscanf', `strftime', `vprintf', `vfprintf' and `vsprintf' whenever such warnings are requested (using `-Wformat'), so there is no need to modify the header file `stdio.h'. In C99 mode, the functions `snprintf', `vsnprintf', `vscanf', `vfscanf' and `vsscanf' are also checked. Except in strictly conforming C standard modes, the X/Open function `strfmon' is also checked as are `printf_unlocked' and `fprintf_unlocked'. *Note Options Controlling C Dialect: C Dialect Options. The target may provide additional types of format checks. *Note Format Checks Specific to Particular Target Machines: Target Format Checks. `format_arg (STRING-INDEX)' The `format_arg' attribute specifies that a function takes a format string for a `printf', `scanf', `strftime' or `strfmon' style function and modifies it (for example, to translate it into another language), so the result can be passed to a `printf', `scanf', `strftime' or `strfmon' style function (with the remaining arguments to the format function the same as they would have been for the unmodified string). For example, the declaration: extern char * my_dgettext (char *my_domain, const char *my_format) __attribute__ ((format_arg (2))); causes the compiler to check the arguments in calls to a `printf', `scanf', `strftime' or `strfmon' type function, whose format string argument is a call to the `my_dgettext' function, for consistency with the format string argument `my_format'. If the `format_arg' attribute had not been specified, all the compiler could tell in such calls to format functions would be that the format string argument is not constant; this would generate a warning when `-Wformat-nonliteral' is used, but the calls could not be checked without the attribute. The parameter STRING-INDEX specifies which argument is the format string argument (starting from one). Since non-static C++ methods have an implicit `this' argument, the arguments of such methods should be counted from two. The `format-arg' attribute allows you to identify your own functions which modify format strings, so that GCC can check the calls to `printf', `scanf', `strftime' or `strfmon' type function whose operands are a call to one of your own function. The compiler always treats `gettext', `dgettext', and `dcgettext' in this manner except when strict ISO C support is requested by `-ansi' or an appropriate `-std' option, or `-ffreestanding' or `-fno-builtin' is used. *Note Options Controlling C Dialect: C Dialect Options. `function_vector' Use this attribute on the H8/300, H8/300H, and H8S to indicate that the specified function should be called through the function vector. Calling a function through the function vector will reduce code size, however; the function vector has a limited size (maximum 128 entries on the H8/300 and 64 entries on the H8/300H and H8S) and shares space with the interrupt vector. You must use GAS and GLD from GNU binutils version 2.7 or later for this attribute to work correctly. On M16C/M32C targets, the `function_vector' attribute declares a special page subroutine call function. Use of this attribute reduces the code size by 2 bytes for each call generated to the subroutine. The argument to the attribute is the vector number entry from the special page vector table which contains the 16 low-order bits of the subroutine's entry address. Each vector table has special page number (18 to 255) which are used in `jsrs' instruction. Jump addresses of the routines are generated by adding 0x0F0000 (in case of M16C targets) or 0xFF0000 (in case of M32C targets), to the 2 byte addresses set in the vector table. Therefore you need to ensure that all the special page vector routines should get mapped within the address range 0x0F0000 to 0x0FFFFF (for M16C) and 0xFF0000 to 0xFFFFFF (for M32C). In the following example 2 bytes will be saved for each call to function `foo'. void foo (void) __attribute__((function_vector(0x18))); void foo (void) { } void bar (void) { foo(); } If functions are defined in one file and are called in another file, then be sure to write this declaration in both files. This attribute is ignored for R8C target. `interrupt' Use this attribute on the ARM, AVR, CRX, M32C, M32R/D, m68k, MS1, and Xstormy16 ports to indicate that the specified function is an interrupt handler. The compiler will generate function entry and exit sequences suitable for use in an interrupt handler when this attribute is present. Note, interrupt handlers for the Blackfin, H8/300, H8/300H, H8S, and SH processors can be specified via the `interrupt_handler' attribute. Note, on the AVR, interrupts will be enabled inside the function. Note, for the ARM, you can specify the kind of interrupt to be handled by adding an optional parameter to the interrupt attribute like this: void f () __attribute__ ((interrupt ("IRQ"))); Permissible values for this parameter are: IRQ, FIQ, SWI, ABORT and UNDEF. On ARMv7-M the interrupt type is ignored, and the attribute means the function may be called with a word aligned stack pointer. `interrupt_handler' Use this attribute on the Blackfin, m68k, H8/300, H8/300H, H8S, and SH to indicate that the specified function is an interrupt handler. The compiler will generate function entry and exit sequences suitable for use in an interrupt handler when this attribute is present. `interrupt_thread' Use this attribute on fido, a subarchitecture of the m68k, to indicate that the specified function is an interrupt handler that is designed to run as a thread. The compiler omits generate prologue/epilogue sequences and replaces the return instruction with a `sleep' instruction. This attribute is available only on fido. `kspisusp' When used together with `interrupt_handler', `exception_handler' or `nmi_handler', code will be generated to load the stack pointer from the USP register in the function prologue. `l1_text' This attribute specifies a function to be placed into L1 Instruction SRAM. The function will be put into a specific section named `.l1.text'. With `-mfdpic', function calls with a such function as the callee or caller will use inlined PLT. `long_call/short_call' This attribute specifies how a particular function is called on ARM. Both attributes override the `-mlong-calls' (*note ARM Options::) command line switch and `#pragma long_calls' settings. The `long_call' attribute indicates that the function might be far away from the call site and require a different (more expensive) calling sequence. The `short_call' attribute always places the offset to the function from the call site into the `BL' instruction directly. `longcall/shortcall' On the Blackfin, RS/6000 and PowerPC, the `longcall' attribute indicates that the function might be far away from the call site and require a different (more expensive) calling sequence. The `shortcall' attribute indicates that the function is always close enough for the shorter calling sequence to be used. These attributes override both the `-mlongcall' switch and, on the RS/6000 and PowerPC, the `#pragma longcall' setting. *Note RS/6000 and PowerPC Options::, for more information on whether long calls are necessary. `long_call/near/far' These attributes specify how a particular function is called on MIPS. The attributes override the `-mlong-calls' (*note MIPS Options::) command-line switch. The `long_call' and `far' attributes are synonyms, and cause the compiler to always call the function by first loading its address into a register, and then using the contents of that register. The `near' attribute has the opposite effect; it specifies that non-PIC calls should be made using the more efficient `jal' instruction. `malloc' The `malloc' attribute is used to tell the compiler that a function may be treated as if any non-`NULL' pointer it returns cannot alias any other pointer valid when the function returns. This will often improve optimization. Standard functions with this property include `malloc' and `calloc'. `realloc'-like functions have this property as long as the old pointer is never referred to (including comparing it to the new pointer) after the function returns a non-`NULL' value. `mips16/nomips16' On MIPS targets, you can use the `mips16' and `nomips16' function attributes to locally select or turn off MIPS16 code generation. A function with the `mips16' attribute is emitted as MIPS16 code, while MIPS16 code generation is disabled for functions with the `nomips16' attribute. These attributes override the `-mips16' and `-mno-mips16' options on the command line (*note MIPS Options::). When compiling files containing mixed MIPS16 and non-MIPS16 code, the preprocessor symbol `__mips16' reflects the setting on the command line, not that within individual functions. Mixed MIPS16 and non-MIPS16 code may interact badly with some GCC extensions such as `__builtin_apply' (*note Constructing Calls::). `model (MODEL-NAME)' On the M32R/D, use this attribute to set the addressability of an object, and of the code generated for a function. The identifier MODEL-NAME is one of `small', `medium', or `large', representing each of the code models. Small model objects live in the lower 16MB of memory (so that their addresses can be loaded with the `ld24' instruction), and are callable with the `bl' instruction. Medium model objects may live anywhere in the 32-bit address space (the compiler will generate `seth/add3' instructions to load their addresses), and are callable with the `bl' instruction. Large model objects may live anywhere in the 32-bit address space (the compiler will generate `seth/add3' instructions to load their addresses), and may not be reachable with the `bl' instruction (the compiler will generate the much slower `seth/add3/jl' instruction sequence). On IA-64, use this attribute to set the addressability of an object. At present, the only supported identifier for MODEL-NAME is `small', indicating addressability via "small" (22-bit) addresses (so that their addresses can be loaded with the `addl' instruction). Caveat: such addressing is by definition not position independent and hence this attribute must not be used for objects defined by shared libraries. `naked' Use this attribute on the ARM, AVR, IP2K and SPU ports to indicate that the specified function does not need prologue/epilogue sequences generated by the compiler. It is up to the programmer to provide these sequences. `near' On 68HC11 and 68HC12 the `near' attribute causes the compiler to use the normal calling convention based on `jsr' and `rts'. This attribute can be used to cancel the effect of the `-mlong-calls' option. `nesting' Use this attribute together with `interrupt_handler', `exception_handler' or `nmi_handler' to indicate that the function entry code should enable nested interrupts or exceptions. `nmi_handler' Use this attribute on the Blackfin to indicate that the specified function is an NMI handler. The compiler will generate function entry and exit sequences suitable for use in an NMI handler when this attribute is present. `no_instrument_function' If `-finstrument-functions' is given, profiling function calls will be generated at entry and exit of most user-compiled functions. Functions with this attribute will not be so instrumented. `noinline' This function attribute prevents a function from being considered for inlining. If the function does not have side-effects, there are optimizations other than inlining that causes function calls to be optimized away, although the function call is live. To keep such calls from being optimized away, put asm (""); (*note Extended Asm::) in the called function, to serve as a special side-effect. `nonnull (ARG-INDEX, ...)' The `nonnull' attribute specifies that some function parameters should be non-null pointers. For instance, the declaration: extern void * my_memcpy (void *dest, const void *src, size_t len) __attribute__((nonnull (1, 2))); causes the compiler to check that, in calls to `my_memcpy', arguments DEST and SRC are non-null. If the compiler determines that a null pointer is passed in an argument slot marked as non-null, and the `-Wnonnull' option is enabled, a warning is issued. The compiler may also choose to make optimizations based on the knowledge that certain function arguments will not be null. If no argument index list is given to the `nonnull' attribute, all pointer arguments are marked as non-null. To illustrate, the following declaration is equivalent to the previous example: extern void * my_memcpy (void *dest, const void *src, size_t len) __attribute__((nonnull)); `noreturn' A few standard library functions, such as `abort' and `exit', cannot return. GCC knows this automatically. Some programs define their own functions that never return. You can declare them `noreturn' to tell the compiler this fact. For example, void fatal () __attribute__ ((noreturn)); void fatal (/* ... */) { /* ... */ /* Print error message. */ /* ... */ exit (1); } The `noreturn' keyword tells the compiler to assume that `fatal' cannot return. It can then optimize without regard to what would happen if `fatal' ever did return. This makes slightly better code. More importantly, it helps avoid spurious warnings of uninitialized variables. The `noreturn' keyword does not affect the exceptional path when that applies: a `noreturn'-marked function may still return to the caller by throwing an exception or calling `longjmp'. Do not assume that registers saved by the calling function are restored before calling the `noreturn' function. It does not make sense for a `noreturn' function to have a return type other than `void'. The attribute `noreturn' is not implemented in GCC versions earlier than 2.5. An alternative way to declare that a function does not return, which works in the current version and in some older versions, is as follows: typedef void voidfn (); volatile voidfn fatal; This approach does not work in GNU C++. `nothrow' The `nothrow' attribute is used to inform the compiler that a function cannot throw an exception. For example, most functions in the standard C library can be guaranteed not to throw an exception with the notable exceptions of `qsort' and `bsearch' that take function pointer arguments. The `nothrow' attribute is not implemented in GCC versions earlier than 3.3. `pure' Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute `pure'. For example, int square (int) __attribute__ ((pure)); says that the hypothetical function `square' is safe to call fewer times than the program says. Some of common examples of pure functions are `strlen' or `memcmp'. Interesting non-pure functions are functions with infinite loops or those depending on volatile memory or other system resource, that may change between two consecutive calls (such as `feof' in a multithreading environment). The attribute `pure' is not implemented in GCC versions earlier than 2.96. `hot' The `hot' attribute is used to inform the compiler that a function is a hot spot of the compiled program. The function is optimized more aggressively and on many target it is placed into special subsection of the text section so all hot functions appears close together improving locality. When profile feedback is available, via `-fprofile-use', hot functions are automatically detected and this attribute is ignored. The `hot' attribute is not implemented in GCC versions earlier than 4.3. `cold' The `cold' attribute is used to inform the compiler that a function is unlikely executed. The function is optimized for size rather than speed and on many targets it is placed into special subsection of the text section so all cold functions appears close together improving code locality of non-cold parts of program. The paths leading to call of cold functions within code are marked as unlikely by the branch prediction mechanism. It is thus useful to mark functions used to handle unlikely conditions, such as `perror', as cold to improve optimization of hot functions that do call marked functions in rare occasions. When profile feedback is available, via `-fprofile-use', hot functions are automatically detected and this attribute is ignored. The `hot' attribute is not implemented in GCC versions earlier than 4.3. `regparm (NUMBER)' On the Intel 386, the `regparm' attribute causes the compiler to pass arguments number one to NUMBER if they are of integral type in registers EAX, EDX, and ECX instead of on the stack. Functions that take a variable number of arguments will continue to be passed all of their arguments on the stack. Beware that on some ELF systems this attribute is unsuitable for global functions in shared libraries with lazy binding (which is the default). Lazy binding will send the first call via resolving code in the loader, which might assume EAX, EDX and ECX can be clobbered, as per the standard calling conventions. Solaris 8 is affected by this. GNU systems with GLIBC 2.1 or higher, and FreeBSD, are believed to be safe since the loaders there save EAX, EDX and ECX. (Lazy binding can be disabled with the linker or the loader if desired, to avoid the problem.) `sseregparm' On the Intel 386 with SSE support, the `sseregparm' attribute causes the compiler to pass up to 3 floating point arguments in SSE registers instead of on the stack. Functions that take a variable number of arguments will continue to pass all of their floating point arguments on the stack. `force_align_arg_pointer' On the Intel x86, the `force_align_arg_pointer' attribute may be applied to individual function definitions, generating an alternate prologue and epilogue that realigns the runtime stack. This supports mixing legacy codes that run with a 4-byte aligned stack with modern codes that keep a 16-byte stack for SSE compatibility. The alternate prologue and epilogue are slower and bigger than the regular ones, and the alternate prologue requires a scratch register; this lowers the number of registers available if used in conjunction with the `regparm' attribute. The `force_align_arg_pointer' attribute is incompatible with nested functions; this is considered a hard error. `returns_twice' The `returns_twice' attribute tells the compiler that a function may return more than one time. The compiler will ensure that all registers are dead before calling such a function and will emit a warning about the variables that may be clobbered after the second return from the function. Examples of such functions are `setjmp' and `vfork'. The `longjmp'-like counterpart of such function, if any, might need to be marked with the `noreturn' attribute. `saveall' Use this attribute on the Blackfin, H8/300, H8/300H, and H8S to indicate that all registers except the stack pointer should be saved in the prologue regardless of whether they are used or not. `section ("SECTION-NAME")' Normally, the compiler places the code it generates in the `text' section. Sometimes, however, you need additional sections, or you need certain particular functions to appear in special sections. The `section' attribute specifies that a function lives in a particular section. For example, the declaration: extern void foobar (void) __attribute__ ((section ("bar"))); puts the function `foobar' in the `bar' section. Some file formats do not support arbitrary sections so the `section' attribute is not available on all platforms. If you need to map the entire contents of a module to a particular section, consider using the facilities of the linker instead. `sentinel' This function attribute ensures that a parameter in a function call is an explicit `NULL'. The attribute is only valid on variadic functions. By default, the sentinel is located at position zero, the last parameter of the function call. If an optional integer position argument P is supplied to the attribute, the sentinel must be located at position P counting backwards from the end of the argument list. __attribute__ ((sentinel)) is equivalent to __attribute__ ((sentinel(0))) The attribute is automatically set with a position of 0 for the built-in functions `execl' and `execlp'. The built-in function `execle' has the attribute set with a position of 1. A valid `NULL' in this context is defined as zero with any pointer type. If your system defines the `NULL' macro with an integer type then you need to add an explicit cast. GCC replaces `stddef.h' with a copy that redefines NULL appropriately. The warnings for missing or incorrect sentinels are enabled with `-Wformat'. `short_call' See long_call/short_call. `shortcall' See longcall/shortcall. `signal' Use this attribute on the AVR to indicate that the specified function is a signal handler. The compiler will generate function entry and exit sequences suitable for use in a signal handler when this attribute is present. Interrupts will be disabled inside the function. `sp_switch' Use this attribute on the SH to indicate an `interrupt_handler' function should switch to an alternate stack. It expects a string argument that names a global variable holding the address of the alternate stack. void *alt_stack; void f () __attribute__ ((interrupt_handler, sp_switch ("alt_stack"))); `stdcall' On the Intel 386, the `stdcall' attribute causes the compiler to assume that the called function will pop off the stack space used to pass arguments, unless it takes a variable number of arguments. `tiny_data' Use this attribute on the H8/300H and H8S to indicate that the specified variable should be placed into the tiny data section. The compiler will generate more efficient code for loads and stores on data in the tiny data section. Note the tiny data area is limited to slightly under 32kbytes of data. `trap_exit' Use this attribute on the SH for an `interrupt_handler' to return using `trapa' instead of `rte'. This attribute expects an integer argument specifying the trap number to be used. `unused' This attribute, attached to a function, means that the function is meant to be possibly unused. GCC will not produce a warning for this function. `used' 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. `version_id' This attribute, attached to a global variable or function, renames a symbol to contain a version string, thus allowing for function level versioning. HP-UX system header files may use version level functioning for some system calls. extern int foo () __attribute__((version_id ("20040821"))); Calls to FOO will be mapped to calls to FOO{20040821}. `visibility ("VISIBILITY_TYPE")' This attribute affects the linkage of the declaration to which it is attached. There are four supported VISIBILITY_TYPE values: default, hidden, protected or internal visibility. void __attribute__ ((visibility ("protected"))) f () { /* Do something. */; } int i __attribute__ ((visibility ("hidden"))); The possible values of VISIBILITY_TYPE correspond to the visibility settings in the ELF gABI. "default" 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,