我想在多个* .c文件中定义(并初始化)结构的多个实例,但我希望它们在编译时收集到单个连续数组中。我一直在研究使用自定义部分,并将该部分的开始和结束地址用作结构体数组的开始和结束,但是我还没有弄清楚细节,我宁愿不编写自定义部分链接器脚本(如果可以的话)。这是我的第一个hack的摘要,它工作不大:

// mystruct.h:
typedef struct { int a; int b; } mystruct;

// mycode1.c:
#include "mystruct.h"
mystruct instance1 = { 1, 2 } __attribute__((section(".mysection")));

// mycode2.c:
#include "mystruct.h"
mystruct instance2 = { 3, 4 } __attribute__((section(".mysection")));

// mystruct.c:
extern char __mysection_start;
extern char __mysection_end;
void myfunc(void) {
    mystruct * p = &__mysection_start;
    for ( ; p < &__mysection_end ; p++) {
        // do stuff using p->a and p->b
    }
}

最佳答案

为了使用自定义节,必须在自定义链接描述文件中定义其起始地址。复制设备的链接描述文件,并将新部分添加到其SECTIONS块中:

/* in custom.gld */
mysection 0x2000 :
{
    *(mysection);
} >data

要使您的对象进入此部分,请使用section属性:
/* mycode1.c: */
#include "mystruct.h"
mystruct __attribute__((section("mysection"))) instance1 = { 1, 2 };

/* mycode2.c: */
#include "mystruct.h"
mystruct __attribute__((section("mysection"))) instance2 = { 3, 4 };

现在,要获取自定义部分的边界,可以使用.startof.(section_name).sizeof.(section_name)汇编器运算符:
#include "mystruct.h"

char *mysection_start;
char *mysection_end;
size_t mysection_size;

int main(void)
{
    asm("mov #.startof.(mysection), W12");
    asm("mov #.sizeof.(mysection), W13");
    asm("mov W12, _mysection_start");
    asm("mov W13, _mysection_size");

    mysection_end = mysection_start + mysection_size;

    mystruct *p = (mystruct *)mysection_start;
    for ( ; (char *)p < mysection_end ; p++)
    {
        // do stuff using p->a and p->b
    }
}

07-24 09:38
查看更多