Compiling a json-c program in Linux

If you have installed json-c in your machine, let’s experiment with a simple JSON program making use of JSON-C functions

#include <json/json.h>
#include <stdio.h>

int main() {
 char * string = "{"name" : "joys of programming"}";
 json_object * jobj = json_tokener_parse(string);
 enum json_type type = json_object_get_type(jobj);
 printf("type: ",type);
 switch (type) {
 case json_type_null: printf("json_type_nulln");
 case json_type_boolean: printf("json_type_booleann");
 case json_type_double: printf("json_type_doublen");
 case json_type_int: printf("json_type_intn");
 case json_type_object: printf("json_type_objectn");
 case json_type_array: printf("json_type_arrayn");
 case json_type_string: printf("json_type_stringn");

Let’s name the above file as json_type.c. Let’s compile it

$ gcc json_type.c

/tmp/ccNekoK9.o: In function `main':
json_type.c:(.text+0x19): undefined reference to `json_tokener_parse'
json_type.c:(.text+0x29): undefined reference to `json_object_get_type'
collect2: ld returned 1 exit status

As you see, there are errors. To compile the program, we must use the “-l” option with the library name “json“. This helps in dynamic loading of the library libjson.

$ gcc json_type.c -l json

It’s successfully compiled. Now let’s execute the program

$ ./a.out
type: json_type_object

See the output of the program. You can learn more about working with json-c.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s