We’ve worked on numerous embedded projects which avoid the use of printf() due to concerns about binary size bloat. Instead, teams will create their own non-standard printf alternative. A classic example is the Arduino SDK’s Print class, which requires users to split print statements into multiple function calls to support different variable display formats.
Rather than rely on a home-spun solution, we recommend using the mpaland/printf library (note: we now recommend the fork maintained by eyalroz, which includes a number of fixes and improvements to the original library). This library was designed specifically for use on embedded systems. It provides support for the printf family of functions, including sprintf, snprintf, and vsnprintf. All of the important formatting flags are provided, including floating point and exponential formats, as well as width and precision specifiers.
The library is re-entrant and thread-safe. There are no dynamic memory allocations, and no static variables or buffers allocated by the library. The code is warning-free, LINT warning free, and tested with 400+ cases. The author also claims it is suitable for use in automotive applications.
Getting this library working on your system is straightforward. There are no external dependencies. All that is needed is an implementation of a _putchar function:
void _putchar(char character)
{
// Add code to print a single character to some device
}
Because the library is targeted for embedded systems usage, options are available to reduce the memory footprint. Internal floating-point buffer sizes can be tuned for your system’s exact needs. Floating point, exponential, and long long printing formats can also be disabled at compile-time.
We love this library. So much so that we use it on client projects, in the Embedded Artistry libc, and in the Embedded Artistry arduino-printf library.
mpaland/printf is released under the MIT license.
Further Reading
eyalroz/printfis an improved fork of the original librarympaland/printfembeddedartistry/libcuses this libraryembeddedartistry/arduino-printfuses this library
