__attribute__((aligned(n)))
内存对齐
使用环境Linux version 4.15.0-29-generic (buildd@lgw01-amd64-057) (gcc version 7.3.0 (Ubuntu 7.3.0-16ubuntu3))
关于设置内存对齐方式上有两种方式:
__attribute__((aligned(n)))
编译器按照n个字节对齐#pragma pack(n)
编译器将按照n个字节对齐;#pragma pack ()
取消指定对齐,恢复缺省对齐
方式一:__attribute__((aligned(n)))
-
一开始去网上找关于它的对齐规则,找到一个十几万阅读,200多收藏的帖子学习,按照设置方式进行测试,发现根本就是错误的(也可能环境不同?这明明是跟编译器有关呀),下面我将用直观的代码形式演示它的正确设置方式!
-
#include <iostream> using namespace std; /* 按照结构体中最大成员类型的字节对齐,最大数据类型是int类型,4个字节 */ struct Test1 { int a; char b; int c; }; /* 【按照aligned(n)中的n】与【结构体中最大数据类型字节数】中的最大值对齐 */ struct Test2 { int a; char b; int c; }__attribute__((aligned(8))); /* 如果aligned(n)中的n填小于结构体中最大数据类型的值, 那么程序员设置的自定义对齐方式是不会生效的 */ /* 按照一个字节对齐 */ struct Test3 { int a; char b; int c; }__attribute__((packed)); // 不等同于__attribute__((aligned(1))); int main() { cout << "sizeof(Test1) = " << sizeof(Test1) << endl; cout << "sizeof(Test2) = " << sizeof(Test2) << endl; cout << "sizeof(Test3) = " << sizeof(Test3) << endl; return 0; }
运行结果:
sizeof(Test1) = 12 sizeof(Test2) = 16 sizeof(Test3) = 9
方式二:#pragma pack(n)
-
#include <iostream> using namespace std; /* 设置内存对齐方式按照1个字节对齐, 如果pack(n)中的n大于结构体中 最大数据类型的值,那么设置会失效,编译器只会按照两者中的最小的那个值对齐, 与aligned(n)正好是相反的 */ #pragma pack(1) struct Test1 { int a; char b; int c; }; /* 恢复默认对齐方式 */ #pragma pack() struct Test2 { int a; char b; int c; }; /* 此时pack(n)中的n大于int的长度,所以会设置失败,编译器 还是会按照四个字节对齐 */ #pragma pack(8) struct Test3 { int a; char b; int c; }; int main() { cout << "sizeof(Test1) = " << sizeof(Test1) << endl; cout << "sizeof(Test2) = " << sizeof(Test2) << endl; cout << "sizeof(Test3) = " << sizeof(Test3) << endl; return 0; }
-
运行结果
sizeof(Test1) = 9 sizeof(Test2) = 12 sizeof(Test3) = 12
这就是两种对齐方式的简单介绍
本人能力有限,如有错误,望不吝指正;原创不易,欢迎转载,转载请注明出处