skip to Main Content

I am pretty new in C++. I would like to include json from that library https://github.com/nlohmann/json. I have downloaded it, put it in my folder

  • MyCPP
    • main.cpp
    • json (nlohmann folder)

In my main.cpp

#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace std;

int main(){
    json j2 = {
        {"pi", 3.141},
        {"happy", true},
    };

    cout << j2 << endl;

    return 0;
}

It says "fatal error: nlohmann/json.hpp: No such file or directory"
I don’t know how I should do to include that folder in my program…

Can anyone explain with much details please.

2

Answers


  1. The ‘nlohmann’ folder should be on the include path of the code you are building.

    Could you please share how you are building the code?

    also, you should use ‘j2.dump()’ to send it to the cout.

    Login or Signup to reply.
  2. If your directory structure is:

    MyCPP /
    |-main.cpp
    |-nlohmann /
      |-json.hpp
    

    Then you should be able to include it by using #include "nlohmann/json.hpp"

    Basically the difference is that <...> searches the system includes, while "..." searches the local includes (it is more complicated if you go into the finer details, but mostly you can ignore that)

    Edit: And of course, if your directory structure looks like this (which it might if you just copied the git repository):

    MyCPP /
    |-main.cpp
    |-nlohmann /
      |-include /
        |-nlohmann /
          |-json.hpp
    

    Then you should be able to include it by using #include "nlohmann/include/nlohmann/json.hpp"

    Edit again, to answer the comment – and BAH! I should have seen that comming:

    The problem there is that the library spans multiple files, and that they include each other. This means that they encounter the same problem as you started out with. There are two fixes to this:

    • The quick and dirty is to #include "json/single_include/nlohmann/json.hpp" – that is the entire library in a single header. The downside to that is that it is big, and that compilation time is likely to be higher.
    • The better solution is to fix your include path so that #include <nlohmann/...> works. I see in another comment that you use g++, so what you need to do there is to add an -I argument with the correct path to it. In your case, that is going to be something like (again pulling from your comment): -I/home/nicolas/Documents/Projects/MyCPP/json/include/. The easiest way is to go to the include dir, use the command pwd, and then copy-paste. Then you should be able to go back to #include <nlohmann/json.hpp>.

    Also, with the second method you don’t need to place the nlohmann library under your project dir, instead you can put it with your other shared libraries and just update the -I path.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search