C之attribute用法

GNU C 的一大特色就是__attribute__ 机制。

__attribute__ 可以设置函数属性(Function Attribute )、变量属性(Variable Attribute )和类型属性(Type Attribute )。

__attribute__ 书写特征是:__attribute__ 前后都有两个下划线,并切后面会紧跟一对原括弧,括弧里面是相应的__attribute__ 参数。

__attribute__ 语法格式为:__attribute__ ((attribute-list))

其位置约束为:放于声明的尾部“ ;” 之前。

关键字__attribute__ 也可以对结构体(struct )或共用体(union )进行属性设置。大致有六个参数值可以被设定,即:aligned, packed, transparent_union, unused, deprecated 和 may_alias 。

在使用__attribute__ 参数时,你也可以在参数的前后都加上“__” (两个下划线),例如,使用__aligned__而不是aligned ,这样,你就可以在相应的头文件里使用它而不用关心头文件里是否有重名的宏定义。

aligned (alignment)

该属性设定一个指定大小的对齐格式(以字节 为单位),例如:

struct S {

扫描二维码关注公众号,回复: 5926502 查看本文章

    short b[3];

} __attribute__ ((aligned (8)));

typedef int int32_t __attribute__ ((aligned (8)));

该声明将强制编译器确保(尽它所能)变量类 型为struct S 或者int32_t 的变量在分配空间时采用8 字节对齐方式。

如上所述,你可以手动指定对齐的格式,同 样,你也可以使用默认的对齐方式。如果aligned 后面不紧跟一个指定的数字值,那么编译器将依据你的目标机器情况使用最大最有益的对齐方式。例如:

struct S {

    short b[3];

} __attribute__ ((aligned));

这里,如果sizeof (short )的大小为2 (byte ),那么,S 的大小就为6 。取一个2 的次方值,使得该值大于等于6 ,则该值为8 ,所以编译器将设置S 类型的对齐方式为8 字节。

aligned 属性使被设置的对象占用更多的空间,相反的,使用packed 可以减小对象占用的空间。

需要注意的是,attribute 属性的效力与你的连接器也有关,如果你的连接器最大只支持16 字节对齐,那么你此时定义32 字节对齐也是无济于事的。

#include<stdio.h>
#include<stdlib.h>


typedef struct{
    char a;
    char b;
}__attribute__((aligned(8))) attr_ali8;

typedef struct{
    char a;
    char b;
}__attribute__((aligned(16))) attr_ali16;

int main()
{
    attr_ali8  a8; 
    attr_ali16 a16;
    int sizeA8  = sizeof(a8);
    int sizeA16 = sizeof(a16);

    printf("___sizeof(attr_ali8): %d\n", sizeA8);
    printf("___sizeof(attr_ali16): %d\n", sizeA16);
}

结果:

___sizeof(attr_ali8): 8
___sizeof(attr_ali16): 16

packed

  使用该属性对struct 或者union 类型进行定义,设定其类型的每一个变量的内存约束。当用在enum 类型 定义时,暗示了应该使用最小完整的类型(it indicates that the smallest integral type should be used)。

#include<stdio.h>
#include<stdlib.h>

typedef struct{
    char a;
    char b;
    int i;
}attr_default; //四字节对齐

typedef struct{
    char a;
    char b;
    int i;
}__attribute__ ((__packed__)) attr_packed;


int main()
{
    attr_default attr_def;
    attr_packed  pattr;
    int sizedef   = sizeof(attr_def);
    int sizePattr = sizeof(pattr);

    printf("___sizeof(attr_def): %d\n", sizedef);
    printf("___sizeof(pattr): %d\n", sizePattr);

结果:

___sizeof(attr_def): 8
___sizeof(pattr): 6

函数属性(Function Attribute)
       函数属性可以帮助开发者把一些特性添加到函数声明中,从而可以使编译器在错误检查方面的功能更强大。__attribute__机制也很容易同非GNU应用程序做到兼容之功效。GNU CC需要使用 –Wall编译器来激活该功能,这是控制警告信息的一个很好的方式。下面介绍几个常见的属性参数。
        __attribute__ format
        该__attribute__属性可以给被声明的函数加上类似printf或者scanf的特征,它可以使编译器检查函数声明和函数实际调用参数之间的格式化字符串是否匹配。该功能十分有用,尤其是处理一些很难发现的bug。
        format的语法格式为:
        format (archetype, string-index, first-to-check)
        format属性告诉编译器,按照printf, scanf, strftime或strfmon的参数表格式规则对该函数的参数进行检查。

        “archetype”指定是哪种风格;

        “string-index”指定传入函数的第几个参数是格式化字符串;

        “first-to-check”指定从函数的第几个参数开始按上述规则进行检查。

具体使用格式如下:
        __attribute__((format(printf,m,n)))
        __attribute__((format(scanf,m,n)))
其中参数m与n的含义为:
m:第几个参数为格式化字符串(format string);
n:参数集合中的第一个,即参数“…”里的第一个参数在函数参数总数排在第几,注意,有时函数参数里还有“隐身”的呢,后面会提到;
在使用上,__attribute__((format(printf,m,n)))是常用的,而另一种却很少见到。下面举例说明,其中myprint为自己定义的一个带有可变参数的函数,其功能类似于printf:

//m=1;n=2
extern void myprint(const char *format,...) __attribute__((format(printf,1,2)));
//m=2;n=3
extern void myprint(int l,const char *format,...) 
__attribute__((format(printf,2,3)));
需要特别注意的是,如果myprint是一个函数的成员函数,那么m和n的值可有点“悬乎”了,例如:
//m=3;n=4
extern void myprint(int l,const char *format,...) 
__attribute__((format(printf,3,4)));
其原因是,类成员函数的第一个参数实际上一个“隐身”的“this”指针。(有点C++基础的都知道点this指针,不知道你在这里还知道吗?)
这里给出测试用例:attribute.c,代码如下:

#include <stdio.h>
#include <stdarg.h>
 
#if 1
#define CHECK_FMT(a, b)    __attribute__((format(printf, a, b)))
#else
#define CHECK_FMT(a, b)
#endif
 
void TRACE(const char *fmt, ...) CHECK_FMT(1, 2);
 
void TRACE(const char *fmt, ...)
{
    va_list ap;
 
    va_start(ap, fmt);
 
    (void)printf(fmt, ap);
 
    va_end(ap);
}
 
int main(void)
{
    TRACE("iValue = %d\n", 6);
    TRACE("iValue = %d\n", "test");
 
    return 0;
}

调试结果:

#if 1 时,

@debian69:~/algoAndSturct/selfTest$ gcc attribute002.c 
@debian69:~/algoAndSturct/selfTest$ gcc attribute002.c -Wall
attribute002.c: In function ‘main’:
attribute002.c:26:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=]
  TRACE("iValue = %d\n", "test");
  ^

#if 0 时,

liubowen@debian69:~/algoAndSturct/selfTest$ gcc attribute002.c 
liubowen@debian69:~/algoAndSturct/selfTest$ gcc attribute002.c -Wall

无任何提示信息

__attribute__ noreturn 

该属性通知编译器函数从不返回值,当遇到类似函数需要返回值而却不可能运行到返回值处就已经退出来的情况,该属性可以避免出现错误信息。C库函数中的abort()和exit()的声明格式就采用了这种格式,如下所示:

extern void exit(int)  __attribute__((noreturn));

extern void abort(void) __attribute__((noreturn));

为了方便理解,大家可以参考如下的例子:

#include<stdio.h>
#include <stdlib.h>

#if 1
void myexit() __attribute__((noreturn));
#else
void myexit();
#endif
void myexit()
{
    exit(0);
}

int main(int argc, char* argv[])
{
    int i = 0;
    if(i > 0)
    {
        myexit();
    }
    else
    {
        return 0;    
    }


调试结果:

#if 0 时,

@debian69:~/algoAndSturct/selfTest$ gcc attribute004.c 
@debian69:~/algoAndSturct/selfTest$ gcc attribute004.c -Wall
attribute004.c: In function ‘main’:
attribute004.c:25:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

由于myexit()直接退出了,所以没有返回值,main函数正常状态下没有错误,但是在-Wall编译下会出现警告

#if 1 时,

@debian69:~/algoAndSturct/selfTest$ gcc attribute004.c 
@debian69:~/algoAndSturct/selfTest$ gcc attribute004.c -Wall

__attribute__ const

       该属性只能用于带有数值类型参数的函数上。当重复调用带有数值参数的函数时,由于返回值是相同的,所以此时编译器可以进行优化处理,除第一次需要运算外, 其它只需要返回第一次的结果就可以了,进而可以提高效率。该属性主要适用于没有静态状态(static state)和副作用的一些函数,并且返回值仅仅依赖输入的参数。
       为了说明问题,下面举个非常“糟糕”的例子,该例子将重复调用一个带有相同参数值的函数,具体如下:

#include<stdio.h>
#include <stdlib.h>

#if 1
int square(int value) __attribute__((const));
#else
int square(int value);
#endif
int square(int value)
{
    return value*value;
}

int main(int argc, char* argv[])
{
    long long i = 0;
    int num = 0;

    for(i = 0; i < 10000000000; i++)
    {
        num = square(5)+i;
    }
}
 

      通过添加__attribute__((const))声明,编译器只调用了函数一次,以后只是直接得到了相同的一个返回值。
事实上,const参数不能用在带有指针类型参数的函数中,因为该属性不但影响函数的参数值,同样也影响到了参数指向的数据,它可能会对代码本身产生严重甚至是不可恢复的严重后果。并且,带有该属性的函数不能有任何副作用或者是静态的状态,所以,类似getchar()或time()的函数是不适合使用该属性的。

__attribute__((constructor)) 在main() 之前执行,

__attribute__((destructor)) 在main()执行结束之后执行.

如果要在main()之前或者是执行完成之后,需要执行很多的前处理动作或者是后处理动作,我们应该怎么处理?

也许,你需要下面这些东西:

__attribute__((constructor(PRIORITY)))

__attribute__((destructor(PRIORITY)))

 PRIORITY: 优先级.

好吧,下面就来试试:

#include<stdio.h>
#include <stdlib.h>

#if 1
__attribute__((constructor(102))) void start_proc1();
__attribute__((destructor(102))) void end_proc1();
__attribute__((constructor(103))) void start_proc2();
__attribute__((destructor(103))) void end_proc2();
#else
__attribute__((constructor(102))) void start_proc1();
__attribute__((destructor(102))) void end_proc1();
__attribute__((constructor(101))) void start_proc2();
__attribute__((destructor(101))) void end_proc2();
#endif

int main(int argc, char* argv[])
{
    return 0;
}

void start_proc1()
{
    printf("___%s\n", __func__);
}
void end_proc1()
{
    printf("___%s\n", __func__);
}
void start_proc2()
{
    printf("___%s\n", __func__);
}
void end_proc2()
{
    printf("___%s\n", __func__);
}

调试结果:

#if 0 时,___start_proc2的优先级大于___start_proc1,end同理

___start_proc2
___start_proc1
___end_proc1
___end_proc2

#if 1 时,___start_proc1的优先级大于___start_proc2,end同理

___start_proc1
___start_proc2
___end_proc2
___end_proc1

注意:构造函数 和 析构函数的优先级0~100,函数内部已使用不能用

猜你喜欢

转载自blog.csdn.net/qq_28090573/article/details/89333652