GCC + C:在二进制文件中保持函数的顺序

GCC + C: Keeping Functions in order in the binary file

我正在为微控制器编写一些代码,我需要根据函数指针查找数据(这些数据和函数将在 ROM 中)。

我希望能够相对快速地执行此操作,并且无需使用 RAM 进行查找 table。我能想到的最简单的方法是进行二进制搜索。

我只是把它作为一个例子,所以它可能会被破坏,但希望你能理解:

void myFunction1() {}
void myFunction2() {}
void myFunction3() {}
void myFunction4() {}
// ...

typedef struct {
  void *functionPtr;
  int myData[10];
} SearchData;

const SearchData mySearchData[] = {
 { &myFunction1, ... },
 { &myFunction2, ... },
 { &myFunction3, ... },
 { &myFunction4, ... },
 // ...
};

void doBinarySearch(void *func, int min, int max) {
  if (max<min) return;
  int mid = (min+max)/2;
  if (func < mySearchData[mid].functionPtr)
    doBinarySearch(func, min, mid-1);
  else if (func > mySearchData[mid].functionPtr)
    doBinarySearch(func, mid+1, max);
  else {
    // we found it!
  }
}

void realBinarySearch(void *func) {
  doBinarySearch(func, 0, (sizeof(mySearchData)/sizeof(SearchData))-1);
}

然而,为了使其工作,myFunction1myFunction2 等需要在内存中一个接一个地布置(尽管不一定彼此相邻)。我需要用 -Os 编译所有内容以适应可用的 ROM,所以 我如何确保函数实际上保持正确的顺序?

...或者失败了,我如何重新排序 mySearchData 使其与函数的顺序相匹配?

我现在唯一能想到的是:

虽然这些听起来都不是很好。

问题的字面答案:
How can I force the order of functions in a binary with the gcc toolchain?
这个linkhttp://sourceware.org/binutils/docs-2.21/ld/Scripts.html#Scripts
这很可怕,但有效

编辑:
方法 2 对查找进行分区 table:
按半字节划分,非常efficient.You只需要一个初始化步骤。分配 16 bytes.read 数组中的所有元素。 “&”函数指针的第一个字节为 0x0F,并在结果偏移量中递增槽。 用你刚刚计算的长度分配 16 个列表。 重新读取数组中的所有元素,这次将它们插入分配的列表中,并使用 16 个字节作为指针放置位置的计数器。
顺便说一句,你有动态内存分配吗?我刚意识到你说的是 8KiB。

好的,。我真的不明白为什么你需要一个指向 SEARCH 的函数指针......将数据放入函数要简单得多,在这种情况下也会重新排序。但是你要求那个。

OK,给出C代码中的gcc:

您可以通过添加以下内容将每个功能放在其自己的部分中:

void f1() __attribute__((section(".text.1")));
void f1()
{
}

void f2() __attribute__((section(".text.2")));
void f2()
{
}

void f3() __attribute__((section(".text.3")));
void f3()
{
}

然后您使用修改后的链接描述文件,如下所示:

 .text   :
  {
   ....
   *(.text.1)
   *(.text.2)
   *(.text.3)
   ... continues here ...

此外,链接器脚本中还有更多可能性可以对输入节进行排序。查看 ld 描述以进行排序!

来自 ld 手册: Normally, the linker will place files and sections matched by wildcards in the order in which they are seen during the link. You can change this by using the SORT keyword, which appears before a wildcard pattern in parentheses (e.g., SORT(.text*)). When the SORT keyword is used, the linker will sort the files or sections into ascending order by name before placing them in the output file.

但顺便说一句,我相信您遇到了 XY 问题。我想你会做一些事情,排序功能和处理二进制搜索是你的解决方案。我相信没有这些 hack 也可以解决 origin 问题!

能得到你原来的问题就好了!