链接器在部分中添加了额外的填充?

时间:2016-09-27 15:39:00

标签: c gcc linker ld

我正在使用GCC并且正在尝试让链接器从自定义部分中的不同文件创建数据对象数组。我已将此部分添加到链接器脚本:

autoupdate=false

这是我的数据结构:

.mydata :
{
  __mydata_start = .;
  KEEP (*(.mydata))
  __mydata_end = .;
}

我在64位平台上,struct my_type_t { unsigned char a; size_t b; void *c; const void *d; const void *e; const char *f; }; 给出48但是,链接器似乎想要将这些结构与64字节对齐。

我的声明:

sizeof(struct my_type_t)

链接器输出:

struct my_type_t a1 __attribute__((section(".mydata"))) = {
    1, 2, (void *)3, (void *)4, (void *)5, (void *)6,
};
struct my_type_t a2 __attribute__((section(".mydata"))) = {
    7, 8, (void *)9, (void *)10, (void *)11, (void *)12,
};

如果我改为将其声明为数组:

$ gcc -o ldtest ldtest.c -Wl,-Tlink.ld
$ objcopy -Obinary -j .mydata ldtest mydata
$ hd mydata
00000000  01 00 00 00 00 00 00 00  02 00 00 00 00 00 00 00  |................|
00000010  03 00 00 00 00 00 00 00  04 00 00 00 00 00 00 00  |................|
00000020  05 00 00 00 00 00 00 00  06 00 00 00 00 00 00 00  |................|
00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000040  07 00 00 00 00 00 00 00  08 00 00 00 00 00 00 00  |................|
00000050  09 00 00 00 00 00 00 00  0a 00 00 00 00 00 00 00  |................|
00000060  0b 00 00 00 00 00 00 00  0c 00 00 00 00 00 00 00  |................|

没有预期的填充:

struct my_type_t a1[2] __attribute__((section(".mydata"))) = {
    {
    1, 2, (void *)3, (void *)4, (void *)5, (void *)6,
    },
    {
    7, 8, (void *)9, (void *)10, (void *)11, (void *)12,
    },
};

为什么链接器会添加超出编译器认为必要的额外填充,以及如何摆脱它?

1 个答案:

答案 0 :(得分:0)

我不知道为什么它希望它在64字节上对齐,但你可以这样做:

struct my_type_t {
    unsigned char a;
    size_t b;
    void *c;
    const void *d;
    const void *e;
    const char *f;
} __attribute__ ((aligned (64)));

要使gcc自动将每个结构填充到最近的64字节地址,并使sizeof(struct my_type_t)也包含填充。这使得这样的操作正常工作:

struct my_type_t *s = &__mydata_start;
s++; // Jump to next entry
s[0]; // First entry
s[1]; // Second entry