Tomás Torres
Tomás Torres

Reputation: 21

cJSON error while compiling and printing file

I recently installed the cJSON library by David Gamble via Cmake and I am getting the following errors:

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

While trying to compile a simple .c code like this:

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;
}

If I add the content of cJSON.c into my code it solves the problem but prints a corrupted file.

Upvotes: 1

Views: 3049

Answers (1)

FSMaxB
FSMaxB

Reputation: 2490

You need to compile it with -lcjson in order to link your code with the installed cJSON library.

Upvotes: 3

Related Questions