Specifying Attributes of Variables

5.31 Specifying Attributes of Variables

The keyword __attribute__ allows you to specify specialattributes of variables or structure fields. This keyword is followedby an attribute specification inside double parentheses. Someattributes are currently defined generically for variables. Other attributes are defined for variables on particular targetsystems. Other attributes are available for functions(see Function Attributes) and for types (see Type Attributes). Other front ends might define more attributes(see Extensions to the C++ Language).

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 __aligned__ instead of aligned.

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

aligned ( alignment )
This attribute specifies a minimum alignment for the variable orstructure field, measured in bytes. For example, the declaration:
          int x __attribute__ ((aligned (16))) = 0;
     

causes the compiler to allocate the global variable x on a16-byte boundary. On a 68040, this could be used in conjunction withan asm expression to access the move16 instruction whichrequires 16-byte aligned operands.

You can also specify the alignment of structure fields. For example, tocreate a double-word aligned int pair, you could write:

          struct foo { int x[2] __attribute__ ((aligned (8))); };
     

This is an alternative to creating a union with a double memberthat forces the union to be double-word aligned.

As in the preceding examples, you can explicitly specify the alignment(in bytes) that you wish the compiler to use for a given variable orstructure field. Alternatively, you can leave out the alignment factorand just ask the compiler to align a variable or field to the maximumuseful alignment for the target machine you are compiling for. Forexample, you could write:

          short array[3] __attribute__ ((aligned));
     

Whenever you leave out the alignment factor in an aligned attributespecification, the compiler automatically sets the alignment for the declaredvariable or field to the largest alignment which is ever used for any datatype on the target machine you are compiling for. Doing this can often makecopy operations more efficient, because the compiler can use whateverinstructions copy the biggest chunks of memory when performing copies toor from the variables or fields that you have aligned this way.

The aligned attribute can only increase the alignment; but youcan decrease it by specifying packed as well. See below.

Note that the effectiveness of aligned attributes may be limitedby inherent limitations in your linker. On many systems, the linker isonly able to arrange for variables to be aligned up to a certain maximumalignment. (For some linkers, the maximum supported alignment maybe very very small.) If your linker is only able to align variablesup to a maximum of 8 byte alignment, then specifying aligned(16)in an __attribute__ will still only provide you with 8 bytealignment. See your linker documentation for further information.

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

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

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

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

deprecated
The deprecated attribute results in a warning if the variableis used anywhere in the source file. This is useful when identifyingvariables that are expected to be removed in a future version of aprogram. The warning also includes the location of the declarationof the deprecated variable, to enable users to easily find furtherinformation about why the variable is deprecated, or what they shoulddo instead. Note that the warning only occurs for uses:
          extern int old_var __attribute__ ((deprecated));
          extern int old_var;
          int new_fn () { return old_var; }
     

results in a warning on line 3 but not line 2.

The deprecated attribute can also be used for functions andtypes (see Function Attributes, see Type Attributes.)

mode ( mode )
This attribute specifies the data type for the declaration—whichevertype corresponds to the mode mode. This in effect lets yourequest an integer or floating point type according to its width.

You may also specify a mode of `byte' or `__byte__' toindicate the mode corresponding to a one-byte integer, `word' or`__word__' for the mode of a one-word integer, and `pointer'or `__pointer__' for the mode used to represent pointers.

packed
The packed attribute specifies that a variable or structure fieldshould have the smallest possible alignment—one byte for a variable,and one bit for a field, unless you specify a larger value with the aligned attribute.

Here is a structure in which the field x is packed, so that itimmediately follows a:

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

section (" section-name ")
Normally, the compiler places the objects it generates in sections like data and bss. Sometimes, however, you need additional sections,or you need certain particular variables to appear in special sections,for example to map to special hardware. The sectionattribute specifies that a variable (or function) lives in a particularsection. For example, this small program uses several specific section names:
          struct duart a __attribute__ ((section ("DUART_A"))) = { 0 };
          struct duart b __attribute__ ((section ("DUART_B"))) = { 0 };
          char stack[10000] __attribute__ ((section ("STACK"))) = { 0 };
          int init_data __attribute__ ((section ("INITDATA"))) = 0;
          
          main()
          {
            /* Initialize stack pointer */
            init_sp (stack + sizeof (stack));
          
            /* Initialize initialized data */
            memcpy (&init_data, &data, &edata - &data);
          
            /* Turn on the serial ports */
            init_duart (&a);
            init_duart (&b);
          }
     

Use the section attribute with an initialized definitionof a global variable, as shown in the example. GCC issuesa warning and otherwise ignores the section attribute inuninitialized variable declarations.

You may only use the section attribute with a fully initializedglobal definition because of the way linkers work. The linker requireseach object be defined once, with the exception that uninitializedvariables tentatively go in the common (or bss) sectionand can be multiply “defined”. You can force a variable to beinitialized with the -fno-common flag or the nocommonattribute.

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.

shared
On Microsoft Windows, in addition to putting variable definitions in a namedsection, the section can also be shared among all running copies of anexecutable or DLL. For example, this small program defines shared databy putting it in a named section shared and marking the sectionshareable:
          int foo __attribute__((section ("shared"), shared)) = 0;
          
          int
          main()
          {
            /* Read and write foo.  All running
               copies see the same value.  */
            return 0;
          }
     

You may only use the shared attribute along with sectionattribute with a fully initialized global definition because of the waylinkers work. See section attribute for more information.

The shared attribute is only available on Microsoft Windows.

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

Not all targets support this attribute.

transparent_union
This attribute, attached to a function parameter which is a union, meansthat the corresponding argument may have the type of any union member,but the argument is passed as if its type were that of the first unionmember. For more details see See Type Attributes. You can also usethis attribute on a typedef for a union data type; then itapplies to all function parameters with that type.
unused
This attribute, attached to a variable, means that the variable is meantto be possibly unused. GCC will not produce a warning for thisvariable.
vector_size ( bytes )
This attribute specifies the vector size for the variable, measured inbytes. For example, the declaration:
          int foo __attribute__ ((vector_size (16)));
     

causes the compiler to set the mode for foo, to be 16 bytes,divided into int sized units. Assuming a 32-bit int (a vector of4 units of 4 bytes), the corresponding mode of foo will be V4SI.

This attribute is only applicable to integral and float scalars,although arrays, pointers, and function return values are allowed inconjunction with this construct.

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

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

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

weak
The weak attribute is described in See Function Attributes.
dllimport
The dllimport attribute is described in See Function Attributes.
dlexport
The dllexport attribute is described in See Function Attributes.
5.31.1 M32R/D Variable Attributes

One attribute is currently defined for the M32R/D.

model ( model-name )
Use this attribute on the M32R/D to set the addressability of an object. 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 theiraddresses can be loaded with the ld24 instruction).

Medium and large model objects may live anywhere in the 32-bit address space(the compiler will generate seth/add3 instructions to load theiraddresses).

5.31.2 i386 Variable Attributes

Two attributes are currently defined for i386 configurations:ms_struct and gcc_struct

ms_struct gcc_struct
If packed is used on a structure, or if bit-fields are usedit may be that the Microsoft ABI packs them differentlythan GCC would normally pack them. Particularly when moving packeddata between functions compiled with GCC and the native Microsoft compiler(either via function call or as data in a file), it may be necessary to accesseither format.

Currently -m[no-]ms-bitfields is provided for the Microsoft Windows X86compilers to match the native Microsoft compiler.

5.31.3 Xstormy16 Variable Attributes

One attribute is currently defined for xstormy16 configurations:below100

below100
If a variable has the below100 attribute ( BELOW100 isallowed also), GCC will place the variable in the first 0x100 bytes ofmemory and use special opcodes to access it. Such variables will beplaced in either the .bss_below100 section or the .data_below100 section.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值