Linking jsoncpp (libjson)

3k Views Asked by At

I'm trying to link jsoncpp (lib_json) with a c++ project using cmake. It works perfectly fine on one computer, but on another one (with pretty much the same config) i get an error when i execute my app :

dyld: Library not loaded: buildscons/linux-gcc-4.2.1/src/lib_json/libjson_linux-gcc-4.2.1_libmt.dylib

Referenced from: path to executable

Reason: image not found

Any idea what might be causing this ? I don't even understand why it tries to look @ buildscons/linux-gcc-4.2.1/src/lib_json/libjson_linux-gcc-4.2.1_libmt.dylib since i put jsoncpp in usr/lib/ and changed the name to libjsoncpp and cmake find the correct path/library.

I also built jsoncpp the exact same way on both computers.

2

There are 2 best solutions below

0
On

I had the same problem. If you run tool -L libjson_linux-gcc-4.2.1_libmt.dylib you can see some weird relative address to your libjson.... I guess if you replicated this directory structure it would work but that's a bad solution.

What I did instead is that I used .a (libjson_linux-gcc-4.2.1_libmt.a) and linked it staticaly with my binary. In XCode simply under Build Settings -> Linking -> Other Linker Flags I added absolute path to my .a. For me it was /Users/martin/Downloads/jsoncpp-src-0.5.0/libs/linux-gcc-4.2.1/libjson_linux-gcc-4.2.1_libmt.a and that's all.

Of course, I don't know your use case, maybe you really need to link it dynamically.

0
On

EDIT: I see now, you mean libjson, and not libjsoncpp (they're different!)

In your titel you talk about jsoncpp, and that's what this answer is for. But maybe it's useful for people who got confused by the titel too.


You can 'amalgamate' jsoncpp.

From jsoncpp source dir run python amalgamate.py which creates:

dist/jsoncpp.cpp
dist/json/json.h
dist/json/json-forwards.h

Now you have to compile jsoncpp.cpp once and just link against the resulting jsoncpp.o:

  1. g++ -o jsoncpp.o -c jsoncpp.cpp (only once)
  2. g++ -o executable jsoncpp.o main.cpp (every time)

If you get errors, you might have to #define JSON_IS_AMALGAMATION before including json/json.h, but ...

... I tried it and it worked for me. (without #define JSON_IS_AMALGAMATION, that is)

Used code:

#include "json/json.h"
#include "json/json-forwards.h"

int main(int argc, char *argv[])
{
    Json::Reader    reader;
    Json::Value     value;
    if (!reader.parse("{\"hello\":\"world\"}", value, false))
    {
        std::cerr << "ERROR: Couldn't parse Json: " << reader.getFormattedErrorMessages() << std::endl;
        return -1;
    }
    std::cout << value.toStyledString() << std::endl;
    return 0;
}