一、功能实现:

① 准备链接器脚本文件,可使用 ld --verbose > link.lds 命令生成。

② 编辑 link.lds 文件,在 .data 段下添加如下内容,以建立自定义数据段。

  .data           :
  {
    *(.data .data.* .gnu.linkonce.d.*)
    SORT(CONSTRUCTORS)
  }

  . = ALIGN(4);
  .MyData          :
  {
    KEEP(*(SORT(.MyDataSection_*)))
  }

③ 三个源码文件,main.c 如下:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include "person.h"
 4
 5 #define MyDataStart(_TYPE) \
 6 ({\
 7     static char start[0] \
 8     __attribute__((unused, section(".MyDataSection_1"))); \
 9     (_TYPE*)start;\
10 })
11
12 #define MyDataEnd(_TYPE) \
13 ({\
14     static char end[0] \
15     __attribute__((unused, section(".MyDataSection_3"))); \
16     (_TYPE*)end;\
17 })
18
19 int main()
20 {
21     PERSON *person = NULL;
22
23     for(person = MyDataStart(PERSON);
24         person < MyDataEnd(PERSON);
25         person++)
26     {
27         if(0 == strcmp(person->name, "lance"))
28             printf("Lance's age is: %d.\n", person->age);
29     }
30
31     return 0;
32 }

④ person.h 如下:

 1 #ifndef _PERSON_H_
 2 #define _PERSON_H_
 3
 4 #pragma pack(4)
 5 typedef struct {
 6     unsigned char     *name;
 7     unsigned int     age;
 8 }PERSON;
 9 #pragma pack()
10
11 #define MyDataListTail(_NAME) \
12 static PERSON _NAME \
13 __attribute__((unused, aligned(4), section(".MyDataSection_2"))) \
14 = {
15
16 #define MyDataListTailEnd() \
17 }
18
19 #endif

⑤ person.c 如下:

 1 #include <stdio.h>
 2 #include "person.h"
 3
 4 MyDataListTail(john)
 5     .name     = "john",
 6     .age    = 14,
 7 MyDataListTailEnd();
 8
 9 MyDataListTail(siri)
10     .name     = "siri",
11     .age    = 15,
12 MyDataListTailEnd();
13
14 MyDataListTail(lance)
15     .name     = "lance",
16     .age    = 16,
17 MyDataListTailEnd();

二、编译命令(需指定链接器脚本)

gcc -Tlink.lds main.c person.c

三、运行结果:

Lance's age is: 16.
01-26 06:15
查看更多