我正在编写一些代码,它将一些数据结构存储在一个特殊的命名二进制部分中.这些是同一结构的所有实例,它们分散在许多C文件中,并且不在彼此的范围内.通过将它们全部放在命名区域中,我可以遍历所有这些区域.
在GCC中,我使用_ attribute _((section(...))加上一些特别命名的extern指针,这些指针由链接器神奇地填充.这是一个简单的例子:
#include <stdio.h>
extern int __start___mysection[];
extern int __stop___mysection[];
static int x __attribute__((section("__mysection"))) = 4;
static int y __attribute__((section("__mysection"))) = 10;
static int z __attribute__((section("__mysection"))) = 22;
#define SECTION_SIZE(sect) \
((size_t)((__stop_##sect - __start_##sect)))
int main(void)
{
size_t sz = SECTION_SIZE(__mysection);
int i;
printf("Section size is %u\n", sz);
for (i=0; i < sz; i++) {
printf("%d\n", __start___mysection[i]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我试图找出如何在MSVC中做到这一点,但我画了一个空白.我从编译器文档中看到我可以使用__pragma(section(...))声明该部分,并使用__declspec(allocate(...))声明数据在该部分中,但我看不出我怎么能得到在运行时指向节的开始和结束的指针.
我在Web上看到了一些与在MSVC中执行_ attribute _((构造函数))相关的示例,但它似乎是特定于CRT的黑客攻击,而不是获取指向节的开头/结尾的指针的一般方法.有人有主意吗?