gcc扩展之类型属性

2018-02-26  本文已影响0人  c096c893940b

引用

  1. gcc5.5 在线手册

属性描述

aligned (alignment)

将结构体的大小与alignment对齐,比如结构体

struct __attribute__((aligned(8))) test
{
    int i;
    char c;
    int j;
};

如果结构体中的变量 i, c , j 都赋值为1。在内存中查看到的layout分别如下:

如果想对齐结构体内某个域,例如在使用netlink时,要求消息的首部必须对齐。可以这样写

struct nlmsg {
    struct __attribute__((aligned(NLMSG_ALIGNTO))){
        struct nlmsghdr nl_hdr;
    };
    struct cn_msg cn_msg;
    enum proc_cn_mcast_op cn_mcast;
};

这样组装出来的消息,头部(nlmsghdr)就是自动对齐的。

上一篇 下一篇

猜你喜欢

热点阅读