MCU中会经常使用printf来打印调试日志,但是编译器默认的printf会使用malloc函数,而且无法自己修改。malloc对于一般MCU平台来说,是有风险的,能不用就不用。
所以移植第三方的printf库函数就是很有必要的事情。
Github下载链接:
本仓库中,查看branch:my-mcu-version。此pirntf库打印都是在栈上进行的,不会使用堆,所以非常安全。
所有修改项已经集中到cJson_Config.h中:
static inline void putchar_(char c)
{
}
/* Support for the decimal notation floating point conversion specifiers (%f, %F), 0 or 1 */
#define PRINTF_SUPPORT_DECIMAL_SPECIFIERS 1
/* Support for the exponential notation floating point conversion specifiers (%e, %g, %E, %G), 0 or 1 */
#define PRINTF_SUPPORT_EXPONENTIAL_SPECIFIERS 1
/* Support for the length write-back specifier (%n), 0 or 1 */
#define PRINTF_SUPPORT_WRITEBACK_SPECIFIER 1
/*
* Support for the long long integral types (with the ll, z and t length modifiers for specifiers
* %d,%i,%o,%x,%X,%u, and with the %p specifier).
* Note: 'L' (long double) is not supported, 0 or 1.
*/
#define PRINTF_SUPPORT_LONG_LONG 1
/*
* 'ntoa' conversion buffer size, this must be big enough to hold one converted
* numeric number including padded zeros (dynamically created on stack)
*/
#define PRINTF_INTEGER_BUFFER_SIZE 32
/*
* size of the fixed (on-stack) buffer for printing individual decimal numbers.
* this must be big enough to hold one converted floating-point value including
* padded zeros.
*/
#define PRINTF_DECIMAL_BUFFER_SIZE 32
/* Default precision for the floating point conversion specifiers (the C standard sets this at 6) */
#define PRINTF_DEFAULT_FLOAT_PRECISION 6
/*
* According to the C languages standard, printf() and related functions must be able to print any
* integral number in floating-point notation, regardless of length, when using the %f specifier -
* possibly hundreds of characters, potentially overflowing your buffers. In this implementation,
* all values beyond this threshold are switched to exponential notation.
*/
#define PRINTF_MAX_INTEGRAL_DIGITS_FOR_DECIMAL 9
/*
* The number of terms in a Taylor series expansion of log_10(x) to
* use for approximation - including the power-zero term (i.e. the
* value at the point of expansion).
*/
#define PRINTF_LOG10_TAYLOR_TERMS 4
/*
* Be extra-safe, and don't assume format specifiers are completed correctly
* before the format string end.
*/
#define PRINTF_CHECK_FOR_NUL_IN_FORMAT_SPECIFIER 1
/*
* Support for msvc style integer specifiers (%I), comment it to disable.
*/
//#define PRINTF_SUPPORT_MSVC_STYLE_INTEGER_SPECIFIERS
移植仅需要修改该头文件中putchar_函数:
1.根据编译器修改其inline定义方式
2.将输出字节的方法添加到函数中
至此我们就可以愉快的使用printf_来进行打印了,函数名比默认的printf多了一个下划线。