编译和打印文件时出现cJSON错误

时间:2016-11-29 03:05:15

标签: c gcc install cjson

我最近通过Cmake安装了David Gamble的cJSON库,我收到以下错误:

gcc prueba.c -lm -o prueba
/tmp/ccdmegU5.o: In function `main':
prueba.c:(.text+0x2e): undefined reference to `cJSON_Parse'
prueba.c:(.text+0x45): undefined reference to `cJSON_GetObjectItem'
prueba.c:(.text+0x60): undefined reference to `cJSON_GetObjectItem'
prueba.c:(.text+0xa2): undefined reference to `cJSON_GetObjectItem'
prueba.c:(.text+0xb2): undefined reference to `cJSON_GetArraySize'
prueba.c:(.text+0xdb): undefined reference to `cJSON_GetArrayItem'
prueba.c:(.text+0xf2): undefined reference to `cJSON_GetObjectItem'
prueba.c:(.text+0x10d): undefined reference to `cJSON_GetObjectItem'
prueba.c:(.text+0x146): undefined reference to `cJSON_Delete'
collect2: error: ld returned 1 exit status

尝试编译一个简单的.c代码时:

int main(int argc, const char * argv[]) {

/*{
    "name": "Mars",
    "mass": 639e21,
    "moons": [
        {
            "name": "Phobos",
            "size": 70
        },
        {
            "name": "Deimos",
            "size": 39
        }
    ]
}*/
char *strJson = "{\"name\" : \"Mars\",\"mass\":639e21,\"moons\":[{\"name\":\"Phobos\",\"size\":70},{\"name\":\"Deimos\",\"size\":39}]}";

printf("Planet:\n");
// First, parse the whole thing
cJSON *root = cJSON_Parse(strJson);
// Let's get some values
char *name = cJSON_GetObjectItem(root, "name")->valuestring;
double mass = cJSON_GetObjectItem(root, "mass")->valuedouble;
printf("%s, %.2e kgs\n", name, mass); // Note the format! %.2e will print a number with scientific notation and 2 decimals
// Now let's iterate through the moons array
cJSON *moons = cJSON_GetObjectItem(root, "moons");
// Get the count
int moons_count = cJSON_GetArraySize(moons);
int i;
for (i = 0; i < moons_count; i++) {
    printf("Moon:\n");
    // Get the JSON element and then get the values as before
    cJSON *moon = cJSON_GetArrayItem(moons, i);
    char *name = cJSON_GetObjectItem(moon, "name")->valuestring;
    int size = cJSON_GetObjectItem(moon, "size")->valueint;
    printf("%s, %d kms\n", name, size);
}

// Finally remember to free the memory!
cJSON_Delete(root);
return 0;
}

如果我将cJSON.c的内容添加到我的代码中,它可以解决问题,但会打印出损坏的文件。

1 个答案:

答案 0 :(得分:1)

您需要使用-lcjson对其进行编译,以便将代码与已安装的cJSON库相链接。