C语言之——__attribute__

时间:2022-07-24
本文章向大家介绍C语言之——__attribute__,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

__attribute__ ((packed)) 的作用就是告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐,是GCC特有的语法。这个功能是跟操作系统没关系,跟编译器有关 。

__attribute__((aligned(4)));设置4字节对齐方式,和#pragma pack(4) 效果一样

可以参考:https://blog.csdn.net/zhangxiong2532/article/details/50826917

#include <stdio.h>

struct mystruct11 
{
    int a;
    char b;
    short c;
}__attribute__((packed));

struct mystruct21 
{
    char a;
    int b;
    short c;
}__attribute__((packed));

struct p  
{  
    int a;  
    char b;  
    char c;  
}__attribute__((aligned(4))) p1;



struct q  
{  
    int a;  
    char b;  
    struct p qn;  
    char c;  
}__attribute__((aligned(8))) q2;

int main(void)
{
    printf("sizeof(struct mystruct11) = %d.n",sizeof(struct mystruct11));
    printf("sizeof(struct mystruct21) = %d.n",sizeof(struct mystruct21));
    /*
    两个不同结构体1字节对齐的结构
    struct mystruct11                         struct mystruct21
    1字节对齐                          1字节对齐
    4                                                   1
    1                                                   4
    2                                                   2
    */
    
    printf("sizeof(int):%d, sizeof(char)=%dn", sizeof(int), sizeof(char));
    printf("sizeof(p1):%dn", sizeof(p1));

    printf("sizeof(q2):%dn", sizeof(q2));
    
    return 0;
}
sizeof(struct mystruct11) = 8.
sizeof(struct mystruct21) = 10.
sizeof(int):4, sizeof(char)=1
sizeof(p1):8
sizeof(q2):24

--------------------------------
Process exited after 0.01857 seconds with return value 0
请按任意键继续. . .