# printf
**Repository Path**: mirrors_mpaland/printf
## Basic Information
- **Project Name**: printf
- **Description**: Tiny, fast, non-dependent and fully loaded printf implementation for embedded systems. Extensive test suite passing.
- **Primary Language**: Unknown
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 1
- **Forks**: 2
- **Created**: 2022-01-06
- **Last Updated**: 2026-11-12
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# A printf / sprintf Implementation for Embedded Systems
[](https://github.com/mpaland/printf/tags)
[](https://github.com/mpaland/printf/actions/workflows/build_and_test.yml)
[](https://github.com/mpaland/printf/actions/workflows/codeql.yml)
[](https://en.cppreference.com/w/c/99)
[](#highlights-and-design-goals)
[](#highlights-and-design-goals)
[](.github/workflows/build_and_test.yml)
[](https://github.com/mpaland/printf/commits/master)
[](https://github.com/mpaland/printf/issues)
[](https://github.com/mpaland/printf/stargazers)
[](LICENSE)
This is a tiny but **fully loaded** printf, sprintf and (v)snprintf implementation.
Primarily designed for usage in embedded systems, where printf is not available due to memory issues or in avoidance of linking against libc.
Using the standard libc printf may pull **a lot** of unwanted library stuff and can bloat code size about 20k or is not 100% thread safe. In this cases the following implementation can be used.
Absolutely **NO dependencies** are required, *printf.c* brings all necessary routines, even its own fast `ftoa` (floating point), `ntoa` (decimal) conversion.
If memory footprint is really a critical issue, floating point, exponential and 'long long' support can be turned off via the `PRINTF_DISABLE_SUPPORT_FLOAT`, `PRINTF_DISABLE_SUPPORT_EXPONENTIAL` and `PRINTF_DISABLE_SUPPORT_LONG_LONG` compiler switches.
When using printf (instead of sprintf/snprintf) you have to provide your own `_putchar()` low level function as console/serial output. If you don't use printf, the `PRINTF_DISABLE_SUPPORT_PUTCHAR` compiler switch removes it, so `_putchar()` isn't needed.
## Status 2026
This library now covers all features of the glibc (C99 scope) without extensions and with the exceptions in the Caveats section below.
I heavily extended the test suite to over 2000 test cases which are all passing.
As of `4.2.1`, there are no known bugs.
## Highlights and Design Goals
There is a boatload of so called 'tiny' printf implementations around. So why this one?
I've tested many implementations, but most of them have very limited flag/specifier support, a lot of other dependencies or are just not standard compliant and failing most of the test suite.
Therefore I decided to write an own, final implementation which meets the following items:
- Very small implementation (around 800 code lines)
- NO dependencies, no libs, just one module file
- Support of all important flags, width and precision sub-specifiers (see below)
- Support of decimal/floating number representation (with an own fast itoa/ftoa)
- Reentrant and thread-safe, malloc free, no static vars/buffers
- LINT and compiler L4 warning free, mature, coverity clean, automotive ready
- Compiling on all main compilers: GCC, Clang and MSVC
- Extensive test suite (> 2000 checks) passing
- Simply the best *printf* around the net
- MIT license
## Usage
Add/link *printf.c* to your project and include *printf.h*. That's it.
A C99 compiler is required (*stdbool.h* and *stdint.h* are used).
With CMake, add this directory via `add_subdirectory()` and link the `printf` library target.
Implement your low level output function needed for `printf()`:
```C
void _putchar(char character)
{
// send char to console etc.
}
```
If you only use `sprintf()`, `snprintf()` and `fctprintf()`, define `PRINTF_DISABLE_SUPPORT_PUTCHAR` when compiling *printf.c* instead. Then `printf()` and `vprintf()` are not provided and no `_putchar()` is needed.
Usage is 1:1 like the according stdio.h library version:
```C
int printf(const char* format, ...);
int sprintf(char* buffer, const char* format, ...);
int snprintf(char* buffer, size_t count, const char* format, ...);
int vsnprintf(char* buffer, size_t count, const char* format, va_list va);
// use output function (instead of buffer) for a streamlike interface
int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...);
int vfctprintf(void (*out)(char character, void* arg), void* arg, const char* format, va_list va);
```
**Due to general security reasons it is highly recommended to prefer and use `snprintf` (with the max buffer size as `count` parameter) instead of `sprintf`.**
`sprintf` has no buffer limitation, so when needed - use it really with care!
### Streamlike Usage
Besides the regular standard `printf()` functions, this module also provides `fctprintf()` (and its `va_list` variant `vfctprintf()`), which takes an output function as first parameter to build a streamlike output like `fprintf()`:
```C
// define the output function
void my_stream_output(char character, void* arg)
{
// opt. evaluate the argument and send the char somewhere
}
{
// in your code
void* arg = (void*)100; // this argument is passed to the output function
fctprintf(&my_stream_output, arg, "This is a test: %X", 0xAA);
fctprintf(&my_stream_output, nullptr, "Send to null dev");
}
```
### Format Checking
With GCC and Clang, the functions are declared with the `format` attribute (the `ATTR_PRINTF` / `ATTR_VPRINTF` macros in *printf.h*), so `-Wformat` (part of `-Wall`) checks the arguments against the format string, like for the standard `printf`.
`%b` is standard since C23 only: GCC warns about it with `-pedantic` and an older C standard, and compilers that don't know `%b` yet always do.
## Format Specifiers
A format specifier follows this prototype: `%[flags][width][.precision][length]type`
The following format specifiers are supported:
### Supported Types
| Type | Output |
|--------|--------|
| d or i | Signed decimal integer |
| u | Unsigned decimal integer |
| b | Unsigned binary |
| o | Unsigned octal |
| x | Unsigned hexadecimal integer (lowercase) |
| X | Unsigned hexadecimal integer (uppercase) |
| f or F | Decimal floating point |
| e or E | Scientific-notation (exponential) floating point |
| g or G | Scientific or decimal floating point |
| c | Single character |
| s | String of characters (a NULL pointer is printed as `(null)`) |
| p | Pointer address (`0x` prefix and lowercase hex digits, zero padded to all digits of the pointer or to the number of digits given by the width; a NULL pointer is printed as `(nil)`, padded to the width like a string) |
| % | A % followed by another % character will write a single % |
### Supported Flags
| Flags | Description |
|-------|-------------|
| - | Left-justify within the given field width; Right justification is the default. |
| + | Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers.
By default, only negative numbers are preceded with a - sign. |
| (space) | If no sign is going to be written, a blank space is inserted before the value. |
| # | Used with o, b, x or X specifiers the value is preceded with 0, 0b, 0x or 0X respectively for values different than zero.
Used with f, F, e, E, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written. With g or G, trailing zeros are not removed. |
| 0 | Left-pads the number with zeros (0) instead of spaces when padding is specified (see width sub-specifier). |
| ' | Thousands grouping flag of POSIX. It is accepted and ignored, no separators are printed. |
### Supported Width
| Width | Description |
|----------|-------------|
| (number) | Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger. |
| * | The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. |
### Supported Precision
| Precision | Description |
|-----------|-------------|
| .number | For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
For f, F, e and E specifiers: this is the number of digits to be printed after the decimal point. **By default, this is 6, maximum is 9** (further digits are printed as 0).
For g and G specifiers: this is the maximum number of significant digits to be printed (trailing zeros are removed).
For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
If the period is specified without an explicit value for precision, 0 is assumed. |
| .* | The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. |
### Supported Length
The length sub-specifier modifies the length of the data type.
| Length | d i | u o x X |
|--------|------|---------|
| (none) | int | unsigned int |
| hh | signed char | unsigned char |
| h | short int | unsigned short int |
| l | long int | unsigned long int |
| ll | long long int | unsigned long long int (truncated to long with PRINTF_DISABLE_SUPPORT_LONG_LONG) |
| j | intmax_t | uintmax_t |
| z | size_t | size_t |
| t | ptrdiff_t | ptrdiff_t (if PRINTF_SUPPORT_PTRDIFF_T is defined) |
For the floating point types (f F e E g G), the length `L` denotes a `long double` argument, which is converted to `double`.
### Return Value
Upon successful return, all functions return the number of characters written, _excluding_ the terminating null character used to end the string.
Functions `snprintf()` and `vsnprintf()` don't write more than `count` bytes, _including_ the terminating null byte ('\0').
Anyway, if the output was truncated due to this limit, the return value is the number of characters that _could_ have been written.
Notice that a value equal or larger than `count` indicates a truncation. Only when the returned value is non-negative and less than `count`,
the string has been completely written.
If any error is encountered, `-1` is returned.
If `buffer` is set to `NULL` (`nullptr`) nothing is written and just the formatted length is returned.
```C
int length = sprintf(NULL, "Hello, world"); // length is set to 12
```
## Compiler Switches/Defines
| Name | Default value | Description |
|------|---------------|-------------|
| PRINTF_INCLUDE_CONFIG_H | undefined | Define this as compiler switch (e.g. `gcc -DPRINTF_INCLUDE_CONFIG_H`) to include a "printf_config.h" definition file |
| PRINTF_NTOA_BUFFER_SIZE | 32 | ntoa (integer) conversion buffer size. This must be big enough to hold one converted numeric number _including_ leading zeros, normally 32 is a sufficient value. Created on the stack |
| PRINTF_FTOA_BUFFER_SIZE | 32 | ftoa (float) conversion buffer size. This must be big enough to hold one converted float number _including_ leading zeros, normally 32 is a sufficient value. Created on the stack |
| PRINTF_DEFAULT_FLOAT_PRECISION | 6 | Define the default floating point precision |
| PRINTF_MAX_FLOAT | 1e9 | Define the largest suitable value to be printed with %f (and %g in decimal notation), before using exponential representation |
| PRINTF_DISABLE_SUPPORT_FLOAT | undefined | Define this to disable floating point (%f) support |
| PRINTF_DISABLE_SUPPORT_EXPONENTIAL | undefined | Define this to disable exponential floating point (%e) support |
| PRINTF_DISABLE_SUPPORT_LONG_LONG | undefined | Define this to disable long long (%ll) support, long long arguments are printed truncated to long then |
| PRINTF_DISABLE_SUPPORT_PTRDIFF_T | undefined | Define this to disable ptrdiff_t (%t) support |
| PRINTF_DISABLE_SUPPORT_PUTCHAR | undefined | Define this to remove `printf()` and `vprintf()`, so no `_putchar()` needs to be implemented when only the sprintf/snprintf/fctprintf functions are used |
## Caveats
The floating point conversion is optimized for size and uses `double` arithmetic. It is not a correctly rounded
conversion like the one of glibc:
- At most 9 digits after the decimal point are computed, further digits are printed as 0.
- The last digit may differ from a correctly rounded result, e.g. `%.1f` of 0.95 prints `1.0` (the binary value of 0.95 is slightly smaller than 0.95).
- Values larger than `PRINTF_MAX_FLOAT` are printed in exponential notation by %f (and %g), instead of printing all digits. With `PRINTF_DISABLE_SUPPORT_EXPONENTIAL` such a value is printed as `ovf` (overflow).
- A `long double` argument (length `L`) is printed with the precision of `double`.
- The specifiers %a and %A and wide characters/strings (%lc, %ls) are not supported.
- %n is not supported and won't be implemented for security reasons: it is the write primitive of format string attacks.
- The arguments of %a, %A and %n are consumed, so the following arguments are printed correctly. The same applies to the floating point specifiers if their support is disabled.
## Test Suite
The test suite in `test/` uses the [Catch2](https://github.com/catchorg/Catch2) v3 framework (vendored as `catch_amalgamated.*`) and links the library compiled as C99. Build and run it with CMake:
```sh
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
```
The test cases are split by topic, one file per topic with a Catch2 tag to run it alone:
| File | Tag | Content |
|------|-----|---------|
| `test_api.cpp` | `[api]` | the functions, their return values and the buffer handling |
| `test_flags.cpp` | `[flags]` | the flags `-` `+` ` ` `#` `0` |
| `test_width_precision.cpp` | `[width]` | field width and precision, also from `*` arguments |
| `test_integers.cpp` | `[integers]` | `%d %i %u %o %x %X %b` and the length modifiers |
| `test_floats.cpp` | `[floats]` | `%f %F %e %E %g %G`, rounding, limits, inf and nan |
| `test_strings_pointers.cpp` | `[strings]` | `%s %c %p %%` |
Checks of behavior beyond the C standard (e.g. `%b`, ignored flags) carry the additional tag `[non-standard]`.
The regression checks of fixed GitHub issues are marked with the issue number. Run a single topic with e.g.
`build/test_suite "[floats]"`.
The compiler switches are available as CMake options, e.g. `-DPRINTF_DISABLE_SUPPORT_FLOAT=ON`, except `PRINTF_DISABLE_SUPPORT_PUTCHAR`: the
`no_putchar` test always checks that the library links without `_putchar()` with it.
With `-DPRINTF_BUILD_AUTOTEST=ON` the `autotest` tool is built, which compares randomly generated format strings and values
against the standard library printf. It runs until stopped, or for `-n COUNT` rounds with the seed `-s SEED`, and exits with 1
if any mismatch was found, e.g. `build/autotest -a -n 1000 -s 42 1>/dev/null` shows only the mismatches. See `autotest -h`.
## Projects Using printf
- [turnkeyboard](https://github.com/mpaland/turnkeyboard) uses printf as log, generic tty and screen formatting output.
- printf is part of [embeddedartistry/libc](https://github.com/embeddedartistry/libc), a libc targeted for embedded systems usage.
- [modm.io](https://modm.io/reference/module/modm-io/#using-printf) is also using this library, albeit with some [hacky hacks](https://github.com/modm-io/modm/blob/develop/src/modm/io/iostream_printf.cpp.in) to disable the native floating point functions on AVR.
(Just create a PR to get *your* project listed here)
## Contributing
0. Give this project a :star:
1. Create an issue and describe your idea
2. [Fork it](https://github.com/mpaland/printf/fork)
3. Create your feature branch (`git checkout -b my-new-feature`)
4. Commit your changes (`git commit -am 'Add some feature'`)
5. Publish the branch (`git push origin my-new-feature`)
6. Create a new pull request
7. Profit! :heavy_check_mark:
## License
printf is written under the [MIT license](http://www.opensource.org/licenses/MIT).