/*
* =====================================================================================
*
* Filename: alignment_demo.c
*
* Description: alignment demo
*
* Version: 1.0
* Created: 07/27/2012 11:34:37 AM
* Revision: none
* Compiler: gcc
*
* Author: TED (gk), guolb57@163.com
*
* =====================================================================================
*/
#include <stdio.h>
struct tag_test_a{
int l;
short i;
char c;
};
typedef struct tag_test_a test_a, *ptest_a;
struct tag_test_b{
short i;
int l;
char c;
};
typedef struct tag_test_b test_b, *ptest_b;
/*属性aligned用于变量、结构或者联合,设定一个指定大小的对齐格式,以字节为单位。
* 但是要注意,这个属性的设定只能用来增加对齐地址而不能减少,例如:
* char c __attribute__((aligned(16))); //让变量 c 以16字节对齐。
* int i __attribute__((aligned(2))); //该aligned属性想要设定变量 i 以2字节对齐,
* //但由于 i 需要4字节对齐。因此该声明无效
*/
struct tag_test_c{
int l;
short i;
char c;
}__attribute__((aligned(8))); /* should be power of 2,
and bigger size of the longest member of structure(here is l) */
typedef struct tag_test_c test_c, *ptest_c;
struct tag_test_d{
short i;
int l;
char c;
}__attribute__((aligned(8)));
typedef struct tag_test_d test_d, *ptest_d;
struct tag_test_e{
short i;
int l;
char c;
}__attribute__((__packed__));
typedef struct tag_test_e test_e, *ptest_e;
struct tag_test_f{
short i;
int l;
char c;
}__attribute__((__packed__));
typedef struct tag_test_f test_f, *ptest_f;
int main(int argc, const char *argv[])
{
/* ********************************************************************** */
/*gcc alignment_demo.c ; ./a.out
* the out put:
* sizeof(test_a) = 8
* sizeof(test_b) = 12
* after aligment:
* sizeof(test_c) = 8
* sizeof(test_d) = 16
* after packed:
* sizeof(test_e) = 7
* sizeof(test_f) = 7 */
/* ********************************************************************** */
printf("sizeof(test_a) = %d\n", sizeof(test_a));
printf("sizeof(test_b) = %d\n", sizeof(test_b));
/* ********************************************************************** */
printf("after aligment:\n");
printf("sizeof(test_c) = %d\n", sizeof(test_c));
printf("sizeof(test_d) = %d\n", sizeof(test_d));
/* ********************************************************************** */
printf("after packed:\n");
printf("sizeof(test_e) = %d\n", sizeof(test_e));
printf("sizeof(test_f) = %d\n", sizeof(test_f));
/* ********************************************************************** */
return 0;
}
注意:1. 在Linux下:在GNU扩展一文中,aligned(ALIGNMENT)的作用是对数据强制对其:
属性aligned用于变量、结构或者联合,设定一个指定大小的对齐格式,以字节为单位。但是要注意,这个属性的设定只能用来增加对齐地址而不能减少,例如:
char c __attribute__((aligned(16))); //让变量 c 以16字节对齐。
int i __attribute__((aligned(2))); //该aligned属性想要设定变量 i 以2字节对齐,但由于 i 需要4字节对齐。因此该声明无效。
2. 在VC环境下,一般地,可以通过下面的方法来改变缺省的对齐条件:
· 使用伪指令#pragma pack(n),编译器将按照n个字节对齐;
· 使用伪指令#pragma pack(),取消自定义字节对齐方式。
3. 注意:如果#pragma pack (n)中指定的n大于结构体中最大成员(类型)的size,则其不起作用,结构体仍然按照size最大的成员进行对齐。
4. 在VC++ 6.0编译器中,我们可以指定其对齐方式,其操作方式为依次选择projetct > setting > C/C++菜单,在struct member alignment中指定你要的对其方式。
5. 使用packed,仅在你需要的时候。