5

I am writing a GUI using a TFT display and the Adafruit GFX library and its default font on Arduino Nano. I want to be memory efficient and I assumed that the 'optimise for size' default setting of the compiler would not compile and include all functions from all included libraries if those functions are never called in the sketch.

However I was reading this memory management guide which advises (on pager 20) to remove 'unused libraries' and 'unused functions' from your sketch to save memory. So I have 2 related questions:

  1. Does the Arduino IDE compiler include all the compiled binary from these library functions even if they are never called in the source sketch (I know that any global variables in a library will take space even if unused but I am specifically asking about unused functions)?

  2. If that is the case would making my own modified, trimmed down, version of the standard libraries save space?

Thanks.

1 Answer 1

7

In general only the functions actually used by your code are included in the final linkage of the binary.

However it's not always possible for the compiler to know what is used and what isn't.

In the case of simple functions and classes there's no problem - the linker is intelligent enough to work it out and only link in the functions that are actually used.

However when it comes to more complex systems with polymorphism or when working with function pointers there are times when the compiler won't really know what is needed and what isn't so sometimes some code gets included that isn't actually wanted.

As the compiler advances those times are getting fewer and farther between, so unless you really have a dire need to reduce your code size there's really nothing much to gain. If you do have that need then you would gain more by reducing the complexity of the code in general and collapsing any polymorphism rather than removing unused functions.

BTW: the "optimize for size" has nothing to do with what code is included / excluded. Instead it controls such things as which function are selected for inline, and what loops are unrolled or not, amongst other things.

2
  • some Arduino cores don't use LTO. for example for the STM32 core by STM the LTO option never produces a working application binary
    – Juraj
    Nov 19, 2020 at 12:25
  • @Juraj It will still only include what is needed. LTO is more for pruning polymorphism. That's the "As the compiler advances..." bit - LTO improves it a massive amount, but there has always been selective inclusion and -ffunction-sections --gc-sections etc.
    – Majenko
    Nov 19, 2020 at 12:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.