gpt4 book ai didi

c - 在编译时将多个文件中的变量收集到一个连续的内存块中

转载 作者:太空狗 更新时间:2023-10-29 15:38:48 25 4
gpt4 key购买 nike

我想在多个 *.c 文件中定义(并初始化)一个结构的多个实例,但我希望它们在编译时聚集到一个连续的数组中。我一直在研究使用自定义部分并将该部分的开始和结束地址用作结构数组的开始和结束,但我还没有完全弄清楚细节,我宁愿不写自定义链接描述文件,如果我能摆脱它的话。这是我的第一次黑客攻击的总结,但不太奏效:

// 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 block 中:

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

要使您的对象进入此部分,请使用部分属性:

/* 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
}
}

关于c - 在编译时将多个文件中的变量收集到一个连续的内存块中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17708212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com