Add RapidJSON with CMake
RapidJSON is a cool and fast C++ library from Tencent for parsing JSON files.
Last time I used it, I wanted to include it with CMake. However, I struggled a little with it. So this post will firstly serve as a reminder for me and secondly make you hopefully struggle less than me.
First of all, we assume a typical CMake project layout:
My_Project ├── CMakeLists.txt ├── include │ └── ... ├── src │ ├── my_project.cc │ ├── ... │ └── local.cmake ├── vendor │ └── rapidjson.cmake └── ...
Download RapidJSON via CMake
CMake can manage external sources as external projects
We now want to use CMake’s
ExternalProject_Add to automatically download and add RapidJSON.
Now the cool thing is that RapidJSON is a “header-only” library, meaning that we can simply copy and include the headers from
rapidjson/include and we can then use everything.
rapidjson.cmake will only download the library from GitHub and then set
RAPIDJSON_INCLUDE_DIR that contains the path to the header files.
With that, our
rapidjson.cmake looks like this:
Include RapidJSON in our Project
CMakeLists.txt we now need to declare two things:
rapidjson.cmakefile exists and should be executed.
RAPIDJSON_INCLUDE_DIRto the list of included directories.
The first step is done by including the following line somewhere in the
CMakeLists.txt file (you probably already have other
include() there as well):
The next step is to add the header files from RapidJSON to the included directories. This can be done with CMake’s
You might already have other included directories there.
In the end, the
CMakeLists.txt might look similar to this:
Add RapidJSON as a Dependency
Now one thing is left before we can actually use RapidJSON. Right now, we only tell CMake what to do and not when to do it.
Thus, we want to add RapidJSON as a dependency to our source code so that it will be downloaded before our code is compiled.
src/local.cmake might look like this:
Now add the following line under
add_executable() in your case):
Now CMake will first download RapidJSON and include its headers and then compile our project.
my_project.cc we can now import RapidJSON!
Now you should be able to run
make and everything should compile.