删除使用 __attribute__((section)) 创建的部分

Remove section created with __attribute__((section))

我有很多功能和相应的单元测试。我想将测试嵌入代码库本身。我提出了以下解决方案:

void a() {
  // this code should be tested
}

__attribute__((section(".tests")))
void a_test() {
  // test if a() works
}

测试放在 .tests 部分中,我可以将其剥离以用于发布版本。我尝试了以下方法:

$ gcc -c a.c -o a.orig.o # a.c is shown above
$ objcopy -R.tests a.orig.o a.o
objcopy: a.o: symbol `.tests' required but not present
objcopy:a.o: no symbols

我发现 this question 描述了一个类似的问题,回答说这是因为该部分正在从某处交叉引用。

我认为 .eh_frame 是有罪的部分,因为删除它会 工作:

$ objcopy -R.tests -R.eh_frame a.orig.o a.o

丢弃链接描述文件中的部分。示例:

SECTIONS {
  /DISCARD/ : { *(.tests) }
}