几年之前,看到关于section的使用百思不得其解,最近又重新探究了。
形如:
struct A
{
int a;
int b;
};
A attribute((used, section(“test”))) a;
A attribute((used, section(“test”))) b;
extern “C” attribute((visibility(“hidden”)))
A __start__test;
extern “C” attribute((visibility(“hidden”)))
A __stop__test;
A* pStart = &__start__test;
while(pStart != &__end__test)
{
pStart++;
}
第一个问题: __start__test和__stop__test 在什么地方定义?
通过objdump -t 查看符号表,的确有对应符号名,start__test地址和 a的地址是一致的,__stop__test指向test section的结束。所以__start和stop应该是编译器自动生成的变量。自己在探究这个问题的时候,动手写了定义,但没有在代码中引用,然后查符号表发现还是没有start和stop,应该是编译器自动优化的结果。
由于end指向的是section的结束为止,所以可以使用std::sort()等使用迭代器的地方前闭后开。
第二个问题:为什么需要在代码中指定section,它的好处有啥,出于什么目的?
目的之一如https://blog.youkuaiyun.com/tang_jin_chan/article/details/9079373
所说可以非常方便注册然后遍历