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?
1 Answer 1
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]
-
You might like to add that the missing
static
forces the compiler to includef()
in the first place. All other stuff is then pulled in by this.the busybee– the busybee02/25/2021 12:03:56Commented Feb 25, 2021 at 12:03 -
@thebusybee: Right, I edited my answer.Edgar Bonet– Edgar Bonet02/25/2021 14:00:24Commented Feb 25, 2021 at 14:00
f()
, it's the fact you're now using theSerial
object, which is massive.f()
static
, as instatic void f() {
will give the compiler enough information to recognize early on thatf
is unused and prevent it from building dependencies forprintln
that it later has to work to figure out whether or not it can eliminate; this is not particularly Arduino related.