embeddedartistry / arduino-printf

Add printf support to the Arduino SDK
MIT License
91 stars 15 forks source link

Implement printf/puts workaround that does not rely on undefined behavior #27

Closed phillipjohnston closed 2 years ago

phillipjohnston commented 2 years ago

I suspect the mpaland approach to the definitions resulted in printf_ being used as the actual name instead of printf w/ the Aliasing option, which avoided the optimization in the past. One workaround is to supply a puts that forwards to printf (what I will do for now, though I suspect that might be undefined behavior). The other workaround is to NOT alias the standard library using the preprocessor option, but instead have LibPrintf.h provide macros like: #define printf printf_ to recreate the old behavior and work with the non-aliased names.

Commented function in code:

/// This works around a problem where GCC is replacing
/// printf("string with no args") with puts("string with no args"), which
/// is not actually implemented in a way that is suitable for us, resulting
/// in an infinite reboot loop or simply not printing that output, depending
/// on my luck.
///
/// This is probably NOT the right way to go about this (expecting it to be undefined
/// behavior, but I have fewer tools available in Arduino land, so I am
/// sticking with this for now.
///
/// If this causes problems in the future, the next thing to try is
/// NOT using the Aliasing option (currently defined in LibPrintf.h) and instead
/// then providing definitions in the mpaland style in our LibPrintf.h header:
/// #define printf printf_
/// #define vprintf vprintf_
/// etc.
extern "C" int puts(const char * str)
{
    return printf("%s\n", str);
}