我试图在二进制文件的部分(如__attribute((__section__("counters")))
)中存储一些变量并对其进行迭代,但我找不到如何获得该部分的起始方向。
阅读 GCC 的文档,我发现(自动?)在我的情况下创建了两个变量__start_counters
和__stop_counters
,但是迭代该内存段似乎不包含我正在寻找的数据。
我的问题是:如何在一个部分中存储一些变量然后获取这些变量?
编辑:
显示我想要实现的目标的最小可编译代码。
#include <stdio.h>
char a, b, c;
struct counter_info {
int counter;
char *name;
} __attribute__((packed));
#define __PUT_STUFF_IN_SECTION(name) \
do{ \
static struct counter_info __counter_info_##name \
__attribute((__section__("counters"))) \
__attribute((__used__)) = { \
.name = #name, \ <--------- this line causes *a lot of* errors, remove to actually compile the code
.counter = 0, \
}; \
}while(0)
extern struct counter_info __start_counters;
extern struct counter_info __stop_counters;
int main(int argc, char **argv){
printf("Start!\n");
__PUT_STUFF_IN_SECTION(a);
__PUT_STUFF_IN_SECTION(b);
__PUT_STUFF_IN_SECTION(c);
struct counter_info *iter = &__start_counters;
for(; iter < &__stop_counters; ++iter){
printf("Name: %s | Counter: %d.\n", &iter->name, &iter->counter);
}
printf("End!\n");
return 0;
}