What am I missing in compiler options for linking with JSON-C static library?

Alex Reynolds picture Alex Reynolds · Nov 19, 2010 · Viewed 9.3k times · Source

I am trying to compile the json-c-0.9 test binaries, while statically linking to libjson.a, which I have built and is sitting in /path/to/json-c-0.9/lib:

$ gcc -g -v -Wall -std=gnu99 -static -L/path/to/json-c-0.9/lib -ljson test1.c -o test1                                                  

I get numerous errors of the form:

/path/to/json-c-0.9/test1.c:17: undefined reference to `json_object_new_string'                                                        
/path/to/json-c-0.9/test1.c:18: undefined reference to `json_object_get_string'                                                        
/path/to/json-c-0.9/test1.c:19: undefined reference to `json_object_to_json_string'                                                    
/path/to/json-c-0.9/test1.c:20: undefined reference to `json_object_put'                                                               
/path/to/json-c-0.9/test1.c:22: undefined reference to `json_object_new_string'
etc.

What I am missing in trying to compile the test binaries? Thanks for your advice.

Answer

逆さま picture 逆さま · Nov 20, 2010

With static linking, gcc only tries to bring in the symbols it needs based on what it has encountered already. In your case, you pass -ljson before your source files, so gcc brings in the static library and doesn't need anything from it, then tries to build your code.

Put the libraries to link against after your code.

$ gcc -g -v -Wall -std=gnu99 -static -L/path/to/json-c-0.9/lib test1.c -o test1 -ljson