我正在为代码/数据 RAM 有限但文件系统使用 RAM 无限的平台开发 C++ 嵌入式应用程序。
在寻找减少代码大小的过程中,我意识到排除 fprintf() 行对生成的代码大小有很大影响。
我的问题是: 1、为什么fprintf的成本这么高? 2. 如果我排除 fprintf 功能,有什么替代方法可以生成描述应用程序运行过程中发生的事件的日志文件?
最佳答案
在嵌入式系统中,printf
有时会拖入对格式字符串的所有浮点支持,如 %f
。
更智能的环境将使 printf
的浮点选项成为可选的东西。
但即使对于整数,printf
中也有很多通用代码,您可能会发现编写自己的例程更紧凑,根据您的特定需求量身定制,喜欢:
outInt (char *buff, int intVal);
outChr (char *buff, char chVal);
outStr (char *buff, char *strVal);
等等,用于写入缓冲区,然后 outBuff (char *buff)
用于将其发送到文件或标准输出。
例如,如果您控制正在使用的数据(无字符串溢出、16 位二进制补整数等),您可以使用以下函数:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void outChr (char *buff, char chVal) {
*buff++ = chVal;
*buff = '\0';
}
void outStr (char *buff, char *strVal) {
strcpy (buff, strVal);
}
void outInt (char *buff, int intVal) {
int divisor = 10000, printing = 0;
// Special cases.
if (intVal == -32768) { outStr (buff, "-32768"); return; }
if (intVal == 0) { outChr (buff, '0'); return; }
// Handle negatives.
if (intVal < 0) { outChr (buff++, '-'); intVal = -intVal; }
// Handle non-zero positives <= 32767.
while (divisor > 0) {
if ((intVal >= divisor) || printing) {
outChr (buff++, "0123456789"[intVal/divisor]);
printing = 1;
}
intVal = intVal % divisor;
divisor /= 10;
}
}
int main (int argc, char *argv[]) {
char buff[1000];
int i;
for (i = 1; i < argc; i++) {
outInt (buff, atoi (argv[i]));
printf ("[%s] -> [%s]\n", argv[i], buff);
}
return 0;
}
运行这个:
pax$ tstprg 32767 10000 9999 10 9 1 0 -1 -9 -10 -99 -10000 -32767 -32768
输出:
[32767] -> [32767]
[10000] -> [10000]
[9999] -> [9999]
[10] -> [10]
[9] -> [9]
[1] -> [1]
[0] -> [0]
[-1] -> [-1]
[-9] -> [-9]
[-10] -> [-10]
[-99] -> [-99]
[-10000] -> [-10000]
[-32767] -> [-32767]
[-32768] -> [-32768]
这些函数的大小应该相对较小,因为它们针对的是特定需求,而不是更通用的 printf
系列。
关于c++ - fprintf 的成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5165654/