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?

zhekaus
  • 459
  • 2
  • 6
  • 18

1 Answers1

7

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]

Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81