一、最近由于项目需要用到json, 目标平台用C语言的,选择用CJson来解析及组json包。
二、cJson的编译非常简单,只需要下载下来的cJSON.c cJSON.h放到项目的工程中编译即可。但是项目所用的平台编译环境只支持简单的Simple C库,cJSON中用到的math.h float.h limits.h均无法使用,导致编译出错,无法找到头文件。
三、解决的方法看看cJSON中用到了那些C库的函数,看是否能自己去实现这些缺少的函数。屏蔽头文件math.h,float.h,limits.h, 编译看看那函数没有。
可以看到,pow(), fabs(), floor(),这个函数没有,以及一些宏定义没有,自己实现这三个函数,百度这三个函数的实现。
static double pow(double x, int n) {
int index = n;
double result = 1;
double sqr;
if (x == 0)
return x;
if (n == 1)
return x;
if (n == 0)
return 1;
if(n < 0)
index = -n;
if (index % 2 == 0) {
// index is even
sqr = pow(x, index / 2);
result = sqr * sqr;
}
else {
// index is odd
sqr = pow(x, (index + 1) / 2);
if (x == 0)
return 1;
result = sqr * sqr / x;
}
if (result == 0)
return 0;
if (n < 0) {
result = 1 / result;
}
return result;
}
static double fabs(double dnumber)
{
*( ( (int *) & dnumber) + 1) &=0x7FFFFFFF;
return dnumber;
}
static int floor(float a)
{
int b=0;
if(a>=0)
{b=(int)a;}
else
{b=(int)a-1;}
return b;
}
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
#define DBL_EPSILON 0.000001
编译通过。