AVR: Code size optimization

Ever wondered why your binary code on the avr is quite big with next to no functions used? This is due to gcc 3.x that links / adds all your functions and relevant includes to the final binary even if some functions are never called. With gcc 4.x unused functions can be removed by the linker.

For more information see this thread on AvrFreaks.

The executive summary:

  • Start from a clean current WinAvr installation
  • Extract gcc 4.11 from AtmanAvr into this directory
  • Extract the recent avr-libc 1.4.5 into this directory
  • Adapt your Linker and Compiler flags accordingly. Add: CFLAGS += -ffunction-sections and LDFLAGS += -Wl,–gc-sections
  • That’s it!

Unfortunalty, this does not work for member functions of classes. So, if you are one of the rare persons developing in C++ for AVR this still does not help 🙁 Back to using IFDEFs again…

Nevertheless, on my projects C++ constructs are only used in special situations like RingBuffer, FiFo etc. Plain C code is optimized and unused functions are removed even if the code is compiled as C++.