1

I am trying to spare a few bytes of program size. I faced a problem which I cannot understand and I hope somebody will help.

Look at this empty sketch, pleas. It takes just 444 bytes:

void setup()
{
}

void loop()
{
}

However, this one – 1332 bytes already!

void f() {
    Serial.println(1);
}


void setup()
{
}

void loop()
{
}

Why? It is supposed that function f() will be cut-off during the linkage stage. But it is not. And what can I do to cut such things off, since they are not used in the code?

6
  • 1
    The problem is not f(), it's the fact you're now using the Serial object, which is massive. – Majenko Feb 24 at 18:54
  • @Majenko Is it possible to optimize it some-how? – zhekaus Feb 24 at 19:18
  • Don't put code in that you don't need? If you want optional code use #ifdef etc to include/exclude it so the compiler never sees it. – Majenko Feb 24 at 19:24
  • @Majenko, As I know, unused code must be optimized during the linkage or so. – zhekaus Feb 24 at 19:29
  • 1
    You may find that making f() static, as in static void f() { will give the compiler enough information to recognize early on that f is unused and prevent it from building dependencies for println that it later has to work to figure out whether or not it can eliminate; this is not particularly Arduino related. – timemage Feb 24 at 19:42
8

Using the Serial object pulls HardwareSerial0.o into your program linkage. This file defines, among other things, the ISRs (interrupt service routines) associated with the serial port. ISRs are defined using the ISR() macro from the acr-libc. This macro creates a function prototype and assigns some attributes to the function, including the used attribute which tells the linker that it should consider the function to be used, even if it cannot spot a single call to it within the compiled program. The ISR cannot then be removed, and it in turn keeps lots of code from the Serial implementation.

Edit: As pointed out by the busybee in a comment, although f() cannot be removed at link time, it can be removed at compile time if you give it the static qualifier. This has the added benefit of triggering a compiler warning:

warning: 'void f()' defined but not used [-Wunused-function]

2
  • You might like to add that the missing static forces the compiler to include f() in the first place. All other stuff is then pulled in by this. – the busybee Feb 25 at 12:03
  • @thebusybee: Right, I edited my answer. – Edgar Bonet Feb 25 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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