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
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.
If your directory structure is:
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):
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:
#include <nlohmann/...>
works. I see in another comment that you useg++
, 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 theinclude
dir, use the commandpwd
, 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.