Declaring Attributes of Functions

来源:互联网 发布:淘宝返利订单权重 编辑:程序博客网 时间:2024/05/21 21:34

Next: Attribute Syntax,Previous: Mixed Declarations,Up: C Extensions


5.24 Declaring Attributes of Functions

In GNU C, you declare certain things about functions called in your programwhich help the compiler optimize function calls and check your code morecarefully.

The keyword __attribute__ allows you to specify specialattributes when making a declaration. This keyword is followed by anattribute specification inside double parentheses. The followingattributes are currently defined for functions on all targets:noreturn, noinline, always_inline,pure,const, nothrow, sentinel,format,format_arg, no_instrument_function,section,constructor, destructor, used,unused,deprecated, weak, malloc,alias,warn_unused_result and nonnull. Several otherattributes are defined for functions on particular target systems. Otherattributes, includingsection are supported for variables declarations(see Variable Attributes) and for types (see Type Attributes).

You may also specify attributes with `__' preceding and followingeach keyword. This allows you to use them in header files withoutbeing concerned about a possible macro of the same name. For example,you may use__noreturn__ instead of noreturn.

See Attribute Syntax, for details of the exact syntax for usingattributes.

alias ("target")
Thealias attribute causes the declaration to be emitted as analias for another symbol, which must be specified. For instance,
          void __f () { /* Do something. */; }          void f () __attribute__ ((weak, alias ("__f")));     

declares `f' to be a weak alias for `__f'. In C++, themangled 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.

always_inline
Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function evenif no optimization level was specified.
cdecl
On the Intel 386, thecdecl attribute causes the compiler toassume that the calling function will pop off the stack space used topass arguments. This isuseful to override the effects of the-mrtd switch.
const
Many functions do not examine any values except their arguments, andhave no effects except the return value. Basically this is just slightlymore strict class than thepure attribute below, since function is notallowed to read global memory.

Note that a function that has pointer arguments and examines the datapointed to mustnot be declared const. Likewise, afunction that calls a non-const function usually must not beconst. It does not make sense for aconst function toreturn void.

The attribute const is not implemented in GCC versions earlierthan 2.5. An alternative way to declare that a function has no sideeffects, 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 languagespecifies that the `const' must be attached to the return value.

constructor
destructor
Theconstructor attribute causes the function to be calledautomatically before execution entersmain (). Similarly, thedestructor attribute causes the function to be calledautomatically aftermain () has completed or exit () hasbeen called. Functions with these attributes are useful forinitializing data that will be used implicitly during the execution ofthe program.

These attributes are not currently implemented for Objective-C.

deprecated
Thedeprecated attribute results in a warning if the functionis used anywhere in the source file. This is useful when identifyingfunctions that are expected to be removed in a future version of aprogram. The warning also includes the location of the declarationof the deprecated function, to enable users to easily find furtherinformation about why the function is deprecated, or what they shoulddo 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 andtypes (seeVariable Attributes, see Type Attributes.)

dllexport
On Microsoft Windows targets and Symbian OS targets thedllexport attribute causes the compiler to provide a globalpointer to a pointer in a DLL, so that it can be referenced with thedllimport attribute. On Microsoft Windows targets, the pointername is formed by combining_imp__ and the function or variablename.

You can use __declspec(dllexport) as a synonym for__attribute__ ((dllexport)) for compatibility with othercompilers.

On systems that support the visibility attribute, thisattribute also implies “default” visibility, unless avisibility attribute is explicitly specified. You should avoidthe use ofdllexport with “hidden” or “internal”visibility; in the future GCC may issue an error for those cases.

Currently, the dllexport attribute is ignored for inlinedfunctions, unless the-fkeep-inline-functions flag has beenused. The attribute is also ignored for undefined symbols.

When applied to C++ classes, the attribute marks defined non-inlinedmember functions and static data members as exports. Static constsinitialized in-class are not marked unless they are also definedout-of-class.

For Microsoft Windows targets there are alternative methods forincluding the symbol in the DLL's export table such as using a.def file with anEXPORTS section or, with GNU ld, usingthe --export-all linker flag.

dllimport
On Microsoft Windows and Symbian OS targets, thedllimportattribute causes the compiler to reference a function or variable viaa global pointer to a pointer that is set up by the DLL exporting thesymbol. The attribute impliesextern storage. On MicrosoftWindows 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 othercompilers.

Currently, the attribute is ignored for inlined functions. If theattribute is applied to a symboldefinition, an error is reported. If a symbol previously declared dllimport is later defined, theattribute is ignored in subsequent references, and a warning is emitted. The attribute is also overridden by a subsequent declaration asdllexport.

When applied to C++ classes, the attribute marks non-inlinedmember functions and static data members as imports. However, theattribute is ignored for virtual methods to allow creation of vtablesusing thunks.

On the SH Symbian OS target the dllimport attribute also hasanother affect—it can cause the vtable and run-time type informationfor a class to be exported. This happens when the class has adllimport'ed constructor or a non-inline, non-pure virtual functionand, for either of those two conditions, the class also has a inlineconstructor or destructor and has a key function that is defined inthe current translation unit.

For Microsoft Windows based targets the use of the dllimportattribute on functions is not necessary, but provides a smallperformance benefit by eliminating a thunk in the DLL. The use of thedllimport attribute on imported variables was required on olderversions of the GNU linker, but can now be avoided by passing the--enable-auto-import switch to the GNU linker. As withfunctions, using the attribute for a variable eliminates a thunk inthe DLL.

One drawback to using this attribute is that a pointer to a functionor variable marked asdllimport cannot be used as a constantaddress. On Microsoft Windows targets, the attribute can be disabledfor 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 specifiedvariable should be placed into the eight bit data section. The compiler will generate more efficient code for certain operationson data in the eight bit data area. Note the eight bit data area is limited to256 bytes of data.

You must use GAS and GLD from GNU binutils version 2.7 or later forthis attribute to work correctly.

far
On 68HC11 and 68HC12 thefar attribute causes the compiler touse a calling convention that takes care of switching memory banks whenentering and leaving a function. This calling convention is also thedefault when using the-mlong-calls option.

On 68HC12 the compiler will use the call and rtc instructionsto call and return from a function.

On 68HC11 the compiler will generate a sequence of instructionsto invoke a board-specific routine to switch the memory bank and call thereal function. The board-specific routine simulates acall. At the end of a function, it will jump to a board-specific routineinstead of usingrts. The board-specific return routine simulatesthe rtc.

fastcall
On the Intel 386, thefastcall attribute causes the compiler topass the first two arguments in the registers ECX and EDX. Subsequentarguments are passed on the stack. The called function will pop thearguments off the stack. If the number of arguments is variable allarguments are pushed on the stack.
format (archetype, string-index,first-to-check)
Theformat attribute specifies that a function takes printf,scanf,strftime or strfmon style arguments whichshould be type-checked against a format string. For example, thedeclaration:
          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_printffor consistency with the printf style format string argumentmy_format.

The parameter archetype determines how the format string isinterpreted, and should beprintf, scanf, strftimeor strfmon. (You can also use__printf__,__scanf__, __strftime__ or __strfmon__.) Theparameter string-index specifies which argument is the formatstring argument (starting from 1), whilefirst-to-check is thenumber of the first argument to check against the format string. Forfunctions where the arguments are not available to be checked (such asvprintf), specify the third parameter as zero. In this case thecompiler only checks the format string for consistency. Forstrftime formats, the third parameter is required to be zero. Since non-static C++ methods have an implicitthis argument, thearguments of such methods should be counted from two, not one, whengiving values forstring-index and first-to-check.

In the example above, the format string (my_format) is the secondargument of the functionmy_print, and the arguments to checkstart with the third argument, so the correct parameters for the formatattribute are 2 and 3.

Theformat attribute allows you to identify your own functionswhich take format strings as arguments, so that GCC can check thecalls to these functions for errors. The compiler always (unless-ffreestanding or-fno-builtin is used) checks formatsfor the standard library functionsprintf, fprintf,sprintf, scanf,fscanf, sscanf, strftime,vprintf,vfprintf and vsprintf whenever suchwarnings are requested (using-Wformat), so there is no need tomodify the header filestdio.h. In C99 mode, the functionssnprintf,vsnprintf, vscanf, vfscanf andvsscanf are also checked. Except in strictly conforming Cstandard modes, the X/Open functionstrfmon is also checked asare printf_unlocked and fprintf_unlocked. See Options Controlling C Dialect.

The target may provide additional types of format checks. See Format Checks Specific to Particular Target Machines.

format_arg (string-index)
Theformat_arg attribute specifies that a function takes a formatstring for aprintf, scanf, strftime orstrfmon style function and modifies it (for example, to translateit into another language), so the result can be passed to aprintf,scanf, strftime or strfmon stylefunction (with the remaining arguments to the format function the sameas they would have been for the unmodified string). For example, thedeclaration:
          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, whoseformat string argument is a call to themy_dgettext function, forconsistency with the format string argumentmy_format. If theformat_arg attribute had not been specified, all the compilercould tell in such calls to format functions would be that the formatstring argument is not constant; this would generate a warning when-Wformat-nonliteral is used, but the calls could not be checkedwithout the attribute.

The parameter string-index specifies which argument is the formatstring argument (starting from one). Since non-static C++ methods havean implicitthis argument, the arguments of such methods shouldbe counted from two.

The format-arg attribute allows you to identify your ownfunctions which modify format strings, so that GCC can check thecalls toprintf, scanf, strftime or strfmontype function whose operands are a call to one of your own function. The compiler always treatsgettext, dgettext, anddcgettext in this manner except when strict ISO C support isrequested by-ansi or an appropriate -std option, or-ffreestanding or-fno-builtinis used. See Options Controlling C Dialect.

function_vector
Use this attribute on the H8/300, H8/300H, and H8S to indicate that the specifiedfunction should be called through the function vector. Calling afunction through the function vector will reduce code size, however;the function vector has a limited size (maximum 128 entries on the H8/300and 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 forthis attribute to work correctly.

interrupt
Use this attribute on the ARM, AVR, C4x, M32R/D and Xstormy16 ports to indicatethat the specified function is an interrupt handler. The compiler willgenerate function entry and exit sequences suitable for use in aninterrupt handler when this attribute is present.

Note, interrupt handlers for the m68k, H8/300, H8/300H, H8S, and SH processorscan be specified via theinterrupt_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 byadding an optional parameter to the interrupt attribute like this:

          void f () __attribute__ ((interrupt ("IRQ")));     

Permissible values for this parameter are: IRQ, FIQ, SWI, ABORT and UNDEF.

interrupt_handler
Use this attribute on the m68k, H8/300, H8/300H, H8S, and SH to indicate thatthe specified function is an interrupt handler. The compiler will generatefunction entry and exit sequences suitable for use in an interrupthandler when this attribute is present.
long_call/short_call
This attribute specifies how a particular function is called onARM. Both attributes override the-mlong-calls (see ARM Options)command line switch and #pragma long_calls settings. Thelong_call attribute causes the compiler to always call thefunction by first loading its address into a register and then using thecontents of that register. Theshort_call attribute always placesthe offset to the function from the call site into the `BL'instruction directly.
longcall/shortcall
On the RS/6000 and PowerPC, thelongcall attribute causes thecompiler to always call this function via a pointer, just as it would ifthe-mlongcall option had been specified. Theshortcallattribute causes the compiler not to do this. These attributes overrideboth the-mlongcall switch and the #pragma longcallsetting.

See RS/6000 and PowerPC Options, for more information on whether longcalls are necessary.

malloc
Themalloc attribute is used to tell the compiler that a functionmay be treated as if any non-NULL pointer it returns cannotalias any other pointer valid when the function returns. This will often improve optimization. Standard functions with this property include malloc andcalloc. realloc-like functions have this property aslong as the old pointer is never referred to (including comparing itto the new pointer) after the function returns a non-NULLvalue.
model (model-name)
On the M32R/D, use this attribute to set the addressability of anobject, and of the code generated for a function. The identifiermodel-name is one of small,medium, orlarge, representing each of the code models.

Small model objects live in the lower 16MB of memory (so that theiraddresses can be loaded with theld24 instruction), and arecallable with the bl instruction.

Medium model objects may live anywhere in the 32-bit address space (thecompiler will generateseth/add3 instructions to load their addresses),and are callable with thebl instruction.

Large model objects may live anywhere in the 32-bit address space (thecompiler will generateseth/add3 instructions to load their addresses),and may not be reachable with thebl instruction (the compiler willgenerate 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 formodel-name issmall, indicating addressability via “small” (22-bit)addresses (so that their addresses can be loaded with theaddlinstruction). Caveat: such addressing is by definition not positionindependent and hence this attribute must not be used for objectsdefined by shared libraries.

naked
Use this attribute on the ARM, AVR, C4x and IP2K ports to indicate that thespecified function does not need prologue/epilogue sequences generated bythe compiler. It is up to the programmer to provide these sequences.
near
On 68HC11 and 68HC12 thenear attribute causes the compiler touse the normal calling convention based onjsr and rts. This attribute can be used to cancel the effect of the-mlong-callsoption.
no_instrument_function
If-finstrument-functions is given, profiling function calls willbe 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 forinlining.
nonnull (arg-index, ...)
Thenonnull attribute specifies that some function parameters shouldbe 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,argumentsdest and src are non-null. If the compilerdetermines that a null pointer is passed in an argument slot markedas non-null, and the-Wnonnull option is enabled, a warningis issued. The compiler may also choose to make optimizations basedon 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, thefollowing 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 asabort and exit,cannot return. GCC knows this automatically. Some programs definetheir own functions that never return. You can declare themnoreturn 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 thatfatal cannot return. It can then optimize without regard to whatwould happen iffatal ever did return. This makes slightlybetter code. More importantly, it helps avoid spurious warnings ofuninitialized variables.

The noreturn keyword does not affect the exceptional path when thatapplies: anoreturn-marked function may still return to the callerby throwing an exception or callinglongjmp.

Do not assume that registers saved by the calling function arerestored before calling thenoreturn function.

It does not make sense for a noreturn function to have a returntype other thanvoid.

The attribute noreturn is not implemented in GCC versionsearlier than 2.5. An alternative way to declare that a function doesnot return, which works in the current version and in some olderversions, is as follows:

          typedef void voidfn ();                    volatile voidfn fatal;     

This approach does not work in GNU C++.

nothrow
Thenothrow attribute is used to inform the compiler that afunction cannot throw an exception. For example, most functions inthe standard C library can be guaranteed not to throw an exceptionwith the notable exceptions ofqsort and bsearch thattake function pointer arguments. Thenothrow attribute is notimplemented in GCC versions earlier than 3.3.
pure
Many functions have no effects except the return value and theirreturn value depends only on the parameters and/or global variables. Such a function can be subjectto common subexpression elimination and loop optimization just as anarithmetic operator would be. These functions should be declaredwith the attributepure. For example,
          int square (int) __attribute__ ((pure));     

says that the hypothetical function square is safe to callfewer 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 thosedepending on volatile memory or other system resource, that may change betweentwo consecutive calls (such as feof in a multithreading environment).

The attribute pure is not implemented in GCC versions earlierthan 2.96.

regparm (number)
On the Intel 386, theregparm attribute causes the compiler topass up to number integer arguments in registers EAX,EDX, and ECX instead of on the stack. Functions that take avariable number of arguments will continue to be passed all of theirarguments on the stack.

Beware that on some ELF systems this attribute is unsuitable forglobal functions in shared libraries with lazy binding (which is thedefault). Lazy binding will send the first call via resolving code inthe loader, which might assume EAX, EDX and ECX can be clobbered, asper the standard calling conventions. Solaris 8 is affected by this. GNU systems with GLIBC 2.1 or higher, and FreeBSD, are believed to besafe since the loaders there save all registers. (Lazy binding can bedisabled with the linker or the loader if desired, to avoid theproblem.)

saveall
Use this attribute on the H8/300, H8/300H, and H8S to indicate thatall registers except the stack pointer should be saved in the prologueregardless of whether they are used or not.
section ("section-name")
Normally, the compiler places the code it generates in thetext section. Sometimes, however, you need additional sections, or you need certainparticular functions to appear in special sections. Thesectionattribute 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 sectionattribute is not available on all platforms. If you need to map the entire contents of a module to a particularsection, consider using the facilities of the linker instead.

sentinel
This function attribute ensures that a parameter in a function call isan explicitNULL. The attribute is only valid on variadicfunctions. By default, the sentinel is located at position zero, thelast parameter of the function call. If an optional integer positionargument P is supplied to the attribute, the sentinel must be located atposition 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-infunctionsexecl and execlp. The built-in functionexecle has the attribute set with a position of 1.

A valid NULL in this context is defined as zero with any pointertype. If your system defines theNULL macro with an integer typethen you need to add an explicit cast. GCC replacesstddef.hwith 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 specifiedfunction is a signal handler. The compiler will generate functionentry and exit sequences suitable for use in a signal handler when thisattribute is present. Interrupts will be disabled inside the function.
sp_switch
Use this attribute on the SH to indicate an interrupt_handlerfunction should switch to an alternate stack. It expects a stringargument that names a global variable holding the address of thealternate stack.
          void *alt_stack;          void f () __attribute__ ((interrupt_handler,                                    sp_switch ("alt_stack")));     

stdcall
On the Intel 386, thestdcall attribute causes the compiler toassume that the called function will pop off the stack space used topass arguments, unless it takes a variable number of arguments.
tiny_data
Use this attribute on the H8/300H and H8S to indicate that the specifiedvariable should be placed into the tiny data section. The compiler will generate more efficient code for loads and storeson data in the tiny data section. Note the tiny data area is limited toslightly under 32kbytes of data.
trap_exit
Use this attribute on the SH for an interrupt_handler to return usingtrapa instead ofrte. This attribute expects an integerargument specifying the trap number to be used.
unused
This attribute, attached to a function, means that the function is meantto be possibly unused. GCC will not produce a warning for thisfunction.
used
This attribute, attached to a function, means that code must be emittedfor the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only ininline assembly.
visibility ("visibility_type")
Thevisibility attribute on ELF targets causes the declarationto be emitted with default, hidden, protected or internal visibility.
          void __attribute__ ((visibility ("protected")))          f () { /* Do something. */; }          int i __attribute__ ((visibility ("hidden")));     

See the ELF gABI for complete details, but the short story is:

default
Default visibility is the normal case for ELF. This value isavailable for the visibility attribute to override other optionsthat may change the assumed visibility of symbols.
hidden
Hidden visibility indicates that the symbol will not be placed intothe dynamic symbol table, so no othermodule (executable orshared library) can reference it directly.
internal
Internal visibility is like hidden visibility, but with additionalprocessor specific semantics. Unless otherwise specified by the psABI,GCC defines internal visibility to mean that the function isnevercalled from another module. Note that hidden symbols, while they cannotbe referenced directly by other modules, can be referenced indirectly viafunction pointers. By indicating that a symbol cannot be called fromoutside the module, GCC may for instance omit the load of a PIC registersince it is known that the calling function loaded the correct value.
protected
Protected visibility indicates that the symbol will be placed in thedynamic symbol table, but that references within the defining modulewill bind to the local symbol. That is, the symbol cannot be overriddenby another module.

Not all ELF targets support this attribute.

warn_unused_result
Thewarn_unused_result attribute causes a warning to be emittedif a caller of the function with this attribute does not use itsreturn value. This is useful for functions where not checkingthe result is either a security problem or always a bug, such asrealloc.
          int fn () __attribute__ ((warn_unused_result));          int foo ()          {            if (fn () < 0) return -1;            fn ();            return 0;          }     

results in warning on line 5.

weak
Theweak attribute causes the declaration to be emitted as a weaksymbol rather than a global. This is primarily useful in defininglibrary functions which can be overridden in user code, though it canalso be used with non-function declarations. Weak symbols are supportedfor ELF targets, and also for a.out targets when using the GNU assemblerand linker.

You can specify multiple attributes in a declaration by separating themby commas within the double parentheses or by immediately following anattribute declaration with another attribute declaration.

Some people object to the__attribute__ feature, suggesting thatISO C's #pragma should be used instead. At the time__attribute__ was designed, there were two reasons for not doingthis.

  1. It is impossible to generate #pragma commands from a macro.
  2. There is no telling what the same #pragma might mean in anothercompiler.

These two reasons applied to almost any application that might have beenproposed for#pragma. It was basically a mistake to use#pragma for anything.

The ISO C99 standard includes _Pragma, which now allows pragmasto be generated from macros. In addition, a#pragma GCCnamespace is now in use for GCC-specific pragmas. However, it has beenfound convenient to use__attribute__ to achieve a naturalattachment of attributes to their corresponding declarations, whereas#pragma GCC is of use for constructs that do not naturally formpart of the grammar. SeeMiscellaneous Preprocessing Directives.

0 0