Use link time optimizations to save flash / program storage space (Sketch too big error)
-
A friend of mine who is way more savvy in c/c++ programming than me mentioned that enabling link time optimizations (LTO) might save some flash space. I decided to do some research and it turns out that LTO is actually supported by the Arduino IDE toolchain, but it is not enabled by default.
I did some digging and figured out how to activate it. These are the results:
GatewaySerial on Atmega328 without LTO:Sketch uses 15,170 bytes (49%) of program storage space. Maximum is 30,720 bytes. Global variables use 711 bytes (34%) of dynamic memory, leaving 1,337 bytes for local variables. Maximum is 2,048 bytes.GatewaySerial on Atmega328 with LTO:
Sketch uses 14,050 bytes (45%) of program storage space. Maximum is 30,720 bytes. Global variables use 712 bytes (34%) of dynamic memory, leaving 1,336 bytes for local variables. Maximum is 2,048 bytes.1,120 bytes flash saved (7.4%)!
SecureActuator on Atmega328 without LTO:
Sketch uses 23,572 bytes (76%) of program storage space. Maximum is 30,720 bytes. Global variables use 1,258 bytes (61%) of dynamic memory, leaving 790 bytes for local variables. Maximum is 2,048 bytes.SecureActuator on Atmega328 with LTO:
Sketch uses 21,242 bytes (69%) of program storage space. Maximum is 30,720 bytes. Global variables use 1,241 bytes (60%) of dynamic memory, leaving 807 bytes for local variables. Maximum is 2,048 bytes.2,330 bytes flash saved (9.9%)!
Pretty sweet!
Here is how to enable it. Shut down the Arduino IDE. Put the following lines:
compiler.c.extra_flags=-flto -fno-fat-lto-objects compiler.c.elf.extra_flags=-flto -fuse-linker-plugin compiler.S.extra_flags=-flto compiler.cpp.extra_flags=-flto compiler.ar.cmd=avr-gcc-arinto a new file at "C:\Program Files (x86)\Arduino\hardware\arduino\avr\platform.local.txt" (or the corresponding place on your OSX/Linux machine)
This might help people trying to fit code into attiny85 or similar mcus with small flash size, or people who try to fit a lot of libraries and/or functionality (for example MY_DEBUG and MY_SIGNING_SOFT at the same time), getting the dreaded "Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it." error.
Caveat: There might be some side-effects of the optimizations. I don't kow what they might be or how common they would be, so please try this and report your results.