1

我最近通过 David Gamble 安装了 cJSON 库,Cmake但出现以下错误:

gcc prueba.c -lm -o prueba
/tmp/ccdmegU5.o:在函数“main”中:
prueba.c:(.text+0x2e): 对“cJSON_Parse”的未定义引用
prueba.c:(.text+0x45): 对“cJSON_GetObjectItem”的未定义引用
prueba.c:(.text+0x60): 对“cJSON_GetObjectItem”的未定义引用
prueba.c:(.text+0xa2): 对“cJSON_GetObjectItem”的未定义引用
prueba.c:(.text+0xb2): 对“cJSON_GetArraySize”的未定义引用
prueba.c:(.text+0xdb): 对“cJSON_GetArrayItem”的未定义引用
prueba.c:(.text+0xf2): 对“cJSON_GetObjectItem”的未定义引用
prueba.c:(.text+0x10d): 对“cJSON_GetObjectItem”的未定义引用
prueba.c:(.text+0x146): 未定义对“cJSON_Delete”的引用
collect2:错误:ld 返回 1 个退出状态

在尝试编译这样的简单 .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 的内容添加到我的代码中,它可以解决问题,但会打印一个损坏的文件。

4

1 回答 1

3

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

于 2017-03-22T10:52:26.633 回答