2011-08-25 55 views
1

全局/局部变量在C如果我创建像将由128位边界对齐这种类型的内存对齐在C

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

所有变量的结构。

这种类型的全局和局部变量是否一样? 或者它不同于编译器和编译器? GCC/LLVM如何处理它们?

+2

请注意,__属性__是GCC特定的内容。此外,并不保证对齐 - 不同的平台可能有基于所涉及的链接器的上限。 – Joe

+1

Micheal在他的回答中提到,涉及两种类型。 'struct A'和'sampleType'别名的类型。这两种类型不一样,'__attribute__'只适用于后者。 AFAIR你可以把'__attribute__'放在'struct'之前应用到那里。无论如何,我发现将这两个声明分开的情况会更加清晰。我会先放一个简单的'typedef struct A sampleType'。 –

回答

1

AFAIK __attribute__是高度依赖于编译器的。与海湾合作委员会,这个计划

#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得到别人面前地址...

2

有一件事是清楚的 - 仅使用sampleType的typedef将强制使用指定的对齐变量。

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

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