celfobjcopy

Remove section created with __attribute__((section))


I have a number of functions and corresponding unit tests. I would like to embed the tests into the codebase itself. I came up with the following solution:

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

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

The tests are placed in a the section .tests which I can strip for release builds. I tried the following:

$ 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

I found this question which describes a similar problem where the answering said that it's because the section is being cross referenced from somewhere.

I think .eh_frame is that guilty section, since removing it will work:

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

Solution

  • Discard the section in a linker script. Example:

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