Chinaunix首页 | 论坛 | 博客
  • 博客访问: 304129
  • 博文数量: 82
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 490
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-13 10:58
文章分类

全部博文(82)

文章存档

2018年(2)

2017年(9)

2016年(71)

我的朋友

分类: C/C++

2016-05-28 08:27:48

1. __attribute__ ((aligned (nbytes)))

功能:给结构体增加字节对其属性

例:

   Typedef struct S {

      short b[3];

   } __attribute__ ((aligned (8))) S1;

说明:使结构体中参数8字节对齐,由于结构体中占内存2*3=6字节,由于设置成8

节对齐,所以该结构体占8字节内存。
 

2.__attribute__((format(printf,m,n)))
__attribute__((format(scanf,m,n)))

功能:给打印类函数增加输入参数检查,因为有些传入参数错误,在编译时使用-Wall

都不会报错。使用该定义,在编译时使用-Wall,则会报出对应的输入参数错误消息。

例:

extern void mypin(int i, const char *s, ...) 

__attribute__((format(printf,2,3)));

void test()

{

        mypin(5, "aaa%s%d", 5);

    }

     使用$gcc -Wall -g test.c –o test编译:

test.c: 8: warning: format ‘%s’ expects type ‘char *’, but

argument 3 has type ‘int’

test.c: 9: warning: too few arguments for format

说明:

1)  void mypin(int i, const char *s, ...)是自己定义的打印类函数,与ptintf()scanf()类似。后面省略的某些参数因该与指定的字符串相关。

2)  format(printf,m,n)中参数:

printf:表示mypin()函数与printf()输入参数类似

scanf: 表示mypin()函数与scanf()输入参数类似

m:      需要检测的字符串是函数的第几个参数

n:      第一个需要与指定字符串对应的参数是函数的第几个参数

注意:在调试中发现,n的位置必须是...(省略号)的参数首位置;而指定的字符串必

须显式的出现在函数参数中,m的位置不可指定在...(省略号)的参数位置。
 

3. __attribute__ ((__packed__))

功能:禁止字节对齐,使内存紧凑分配。

例:

    typedef struct Pt {

       char a;

       short b;

    } P;

    typedef struct Pt1 {

       char a;

       short b;

       P c;

    }P1;

    typedef struct Pt2 {

       char a;

       short b;

       P c;

    } __attribute__ ((__packed__)) P2;

输出结果:

    sizeof(P) [4];

    sizeof(P1) [8];

sizeof(P2) [7];

说明:

1) P原本3个字节,因为4字节对齐,所以其大小为4

2) P1a+b=3,由于c4字节,所以a+b实际占4字节,总大小8字节。

3) P2a+b不字节对齐,即占3字节,c的结构体并未禁止字节对齐,所以占4字节。总大小7字节。

注意:P也禁止了字节对齐,那么P2的大小应该为6字节。

阅读(657) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~