C中全局/局部变量的内存对齐

时间:2011-08-25 04:44:29

标签: c gcc memory-management compiler-construction

如果我创建了像

这样的结构,请在C中
typedef struct A
{
  int a;
  char b;
} sampleType __attribute__ ((aligned (128)));

此类型的所有变量将通过128位边界对齐。

此类型的全局变量和局部变量是否相同? 或者它与编译器有什么不同? GCC / LLVM如何处理它们?

2 个答案:

答案 0 :(得分:2)

有一点需要明确 - 只有使用sampleType typedef的变量才会强制执行指定的对齐。

使用struct A声明的变量不会。

此语法是GCC扩展 - 其他编译器可能支持也可能不支持(MSVC不支持,我不知道LLVM是否支持)。

答案 1 :(得分:1)

AFAIK __attribute__高度依赖编译器。用gcc,这个程序

#include <stdio.h>

typedef struct st
{
  int a;
  char b;
} st __attribute__ ((aligned (128)));

static char a;
static st b;
static char c;
static struct st d;

char e;
st f;
char g;
struct st h;

int main()
{
    char i;
    st j;
    char k;
    struct st l;

    printf("%p %p %p %p\n", &a, &b, &c, &d);
    printf("%p %p %p %p\n", &e, &f, &g, &h);
    printf("%p %p %p %p\n", &i, &j, &k, &l);
}

给了我

0x804a100 0x804a180 0x804a188 0x804a18c
0x804a208 0x804a280 0x804a288 0x804a200
0xbfc8d87f 0xbfc8d800 0xbfc8d7ff 0xbfc8d7f4

这告诉了什么?

如果真的使用typedef ed类型(st),则会发生对齐。如果我使用struct st,则不会。

如果发生这种情况,它会发生在static个变量,external链接的变量上,以及automatic变量上(在堆栈上)。

让我感到困惑的是,h在其他人之前得到了一个地址......