2

I would like to know if I can tell gcc/ld to omit unused modules from being put into the output file.

Suppose I have modules a.c, b.c and c.c. a.c and b.c depend on each other, one of them contains a main(), and due to whatever reasons, no parts of c.c are referenced.

gcc -c a.c
gcc -c b.c
gcc -c c.c

If I bundle the stuff together into a library, no code from c.c won't be in the output:

ar rcs abc.a a.o b.o c.o
gcc abc.a

But if I give the .o files directly to gcc, the code from c.c resp. c.o is included.

gcc a.o b.o c.o

Can I, by any way, tell gcc to leave out unused modules without putting them into a library?

I am programming an AVR µC and use AVR Studio, which doesn't allow the creation of libraries, but would like to omit the source files which are not used, depending on the build configuration.

glglgl
  • 89,107
  • 13
  • 149
  • 217

1 Answers1

3

I don't know if it's possible on AVR, but you could ask GCC to put each symbols in its own section using -ffunction-sections -fdata-sections at compile time. Then at link step, you could use -Wl,--gc-sections to ask ld to remove unused sections.

Yann Droneaud
  • 5,277
  • 1
  • 23
  • 39
  • Sounds great. I just found a switch which enables this "gc-sections". Does it as well work on a per-module basis without `-ffunction-sections -fdata-sections`? I don't want to get the ISR routines to be thrown out... – glglgl Feb 24 '12 at 14:54
  • @glglgl according to its name, it's only per sections, not per module. So if your ISR are not referenced by anything in the rest of the code, it's going to be discarded by the linker. – Yann Droneaud Feb 24 '12 at 14:56
  • Oh, I thought that every module has some own sections which get discarded then... After some testing, it turns out that this indeed seems to be the case. – glglgl Feb 24 '12 at 15:10
  • If you want to know which sections `ld` throws out, you can also add `-Wl,--print-gc-sections` to the linker command line. – ndim Aug 13 '17 at 23:43