Problem with compiler optimisatioon and sprintf

Manu

Well-known member
Hello,

I found a problem that make the µC behave different depending the "optimize" option one use. This happen with "sprintf" command.

Code:
float exemple = 1.;

void setup() {
  char test[200];
  Serial.begin (115200);
  while ((!Serial) && (millis() < 500) );
  sprintf (test, "%f", exemple);
  Serial.write (test, strlen(test));
  Serial.println();
}

void loop() {
  // put your main code here, to run repeatedly:

}

If I use "Faster", all behave as expected. Serial console display 1.00000
If I use "Smallest Code with LTO", nothing happen. Serial console display nothing.

Just something that make me was many time ;-)
I'm sure this is an Arduino thing and not a PJRC thing, but I don't know how to get in touch with Arduino devs.

Best regards,
Manu
 
I can reproduce that.
The reason seems to be that all(?) "Smallest Code" settings lead to the compiler flag --specs=nano.specs. This replaces the standard libraries with smaller ones (*_nano). Looks like the nano libraries don't implement printf, sprintf etc.. If you remove the --specs flag everything works as expected but of course the executable gets larger. This is obviously contra productive to the smallest code setting.
Looks like using printf and friends and choosing size optimization are mutually exclusive which somehow does make sense.


I'm sure this is an Arduino thing and not a PJRC thing, but I don't know how to get in touch with Arduino devs.
No, the compiler flags are set by the Teensy Boards.txt. Anyway, I'd definitely call that a feature not a bug...
 
Looks like the nano libraries don't implement printf, sprintf etc..

The smaller nano C library does implement printf, but not for floating point numbers. You can still use Serial.printf("%d", myint) and and all the other stuff printf() does, except for floating point numbers.

If you need to print floats, you can still use the Arduino way with Serial.print(myfloat, digits). But it is limited in numerical range, which usually isn't an issue for most uses... but not as powerful and flexible as the normal not-nano printf.

The code size and default memory usage of the nano C library is *much* lower than the normal C lib. If we didn't use this for the "smallest size" menu option, your project would have about 20K of extra code and about 2K of extra RAM usage. That's why it's done when you select "smallest size".
 
Hello,

I can reproduce that.
Anyway, I'd definitely call that a feature not a bug...

I never said that this is a bug. It was something I figure out and I want to share.

Anyway, thank you all for your answers.
Best regards,
Manu
 
Back
Top