Using nlohmann/json in Your C++ Project with CMake
The nlohmann/json library, also known as JSON for Modern C++, is a popular choice for JSON manipulation in C++ due to its ease of use, extensive documentation, and modern C++ standards compliant design. When it comes to distributing your project or managing its dependencies, you have several options. Below, we will discuss how to integrate nlohmann/json using CMake, which is a powerful cross-platform tool that automates the build process.
Option 1: Including the Header File Directly
If your project is relatively small and you prefer to keep things simple, you might choose to directly include the nlohmann/json.hpp header file in your project. This is the most straightforward approach and doesn't require CMake adjustments. However, it's less scalable and might not be the best choice for larger projects or those with more complex dependency management needs.
Option 2: Using FetchContent (CMake 3.11+)
For a more scalable solution, you can use CMake's FetchContent module, introduced in CMake 3.11, which allows you to download dependencies during the configure phase. This is an excellent way to include nlohmann/json in your project since it does not require manually downloading or tracking the library in your repository.
Here's a basic example of how to do it:
cmake_minimum_required(VERSION 3.11)
project(YourProjectName)
include(FetchContent)
FetchContent_Declare(
json
GIT_REPOSITORY https://github.com/nlohmann/json.git
GIT_TAG v3.10.5 # Specify the version you want to use
)
FetchContent_GetProperties(json)
if(NOT json_POPULATED)
FetchContent_Populate(json)
add_subdirectory(${json_SOURCE_DIR} ${json_BINARY_DIR} EXCLUDE_FROM_ALL)
endif()
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} nlohmann_json::nlohmann_json)
Option 3: Using add_subdirectory with Submodule or External Project
If you already have or prefer to add nlohmann/json as a Git submodule or you've downloaded it into your project's directory, you can use the add_subdirectory command to include it:
-
As a Git Submodule:
First, add nlohmann/json as a submodule:
git submodule add https://github.com/nlohmann/json.git external/json
git submodule update --init
Then, in your CMakeLists.txt:
add_subdirectory(external/json)
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} nlohmann_json::nlohmann_json)
-
Manually Placed in Your Project:
If you manually added the library into a project subdirectory, the CMakeLists.txt setup would be similar to the submodule approach.
Option 4: Using a Package Manager
If your project uses a package manager such as vcpkg or conan, you might find it easier to manage nlohmann/json and other dependencies through those tools. Both vcpkg and conan support nlohmann/json and can integrate smoothly with CMake.
Example with vcpkg:
vcpkg install nlohmann-json
Then, integrate with CMake either through the toolchain file provided by vcpkg or by setting CMAKE_TOOLCHAIN_FILE to the path of the vcpkg toolchain file.
Example with Conan:
- Add
nlohmann_json/x.y.z to your conanfile.txt or conanfile.py.
- Install the dependencies using
conan install.
- Use the generated
conanbuildinfo.cmake in your CMake project.
Conclusion
Choosing the right integration method depends on your project's needs, the complexity of your dependency management, and personal preference. For most projects, using FetchContent offers a good balance between ease of use and flexibility, allowing you to specify the exact nlohmann/json version and ensure all developers and CI environments use the same library version without additional manual setup.
The confusion around json_SOURCE_DIR is understandable, especially if you're relatively new to CMake's FetchContent module. Let me clarify that part for you.
In the context of the CMake script using FetchContent to fetch nlohmann/json, json_SOURCE_DIR and json_BINARY_DIR are variables automatically defined by the FetchContent module after calling FetchContent_Populate(json). You do not need to manually define or replace them with specific folders.
Here's a brief explanation of each:
-
json_SOURCE_DIR: This variable will hold the path to the source directory where the fetched content (in this case, the nlohmann/json library) has been downloaded and placed. This directory contains the source files, including CMakeLists.txt and other necessary files for building the library.
-
json_BINARY_DIR: Similarly, this variable will hold the path to the binary directory where the fetched content will be built. This location is where CMake will generate the build files for the nlohmann/json library.
The FetchContent_Populate(json) function takes care of downloading the library's source code into the directory specified by json_SOURCE_DIR and preparing it for the build process in json_BINARY_DIR.
You don't need to manually create these directories or substitute these variables with actual paths. The FetchContent_Declare(...) and FetchContent_Populate(json) commands handle everything automatically. These variables (json_SOURCE_DIR and json_BINARY_DIR) are used in the subsequent add_subdirectory(${json_SOURCE_DIR} ${json_BINARY_DIR} EXCLUDE_FROM_ALL) command to include the fetched library in your project's build.
Here's a simplified step-by-step of what happens:
-
FetchContent_Declare specifies where to download the content from (the GitHub repository in this case) and optionally which tag to use.
-
FetchContent_GetProperties(json) checks if the content defined by the json label has been fetched.
-
If NOT json_POPULATED, FetchContent_Populate(json) is called to actually fetch the content (download or update the nlohmann/json library), populating json_SOURCE_DIR with the directory containing the fetched source code, and json_BINARY_DIR with the directory to hold build files.
-
add_subdirectory(${json_SOURCE_DIR} ${json_BINARY_DIR}) then uses these directories to include the nlohmann/json library into your project as if it were part of your source tree, making it available for building and linking.
By using these provided variables, you instruct CMake to build the nlohmann/json library alongside your project automatically, without needing to worry about downloading, extracting, and specifying correct paths by yourself.
Performing a clean build in a project configured with CMake is a commonly required operation, especially when you want to ensure that previous build artifacts do not affect the current build process. However, the way CMake is designed, it doesn't directly provide a "clean" command like make clean. Here's how you can achieve a clean build in various scenarios:
Using Makefile generator (UNIX-based systems):
If you're using a Makefile generator with CMake (the default on UNIX-based systems), and have already run cmake to configure the project and make to build it, you can clean up most build artifacts using:
make clean
However, this command doesn't remove everything (e.g., CMake cache files, and potentially other directories/files you've configured CMake to create outside of the default CMake build directory). To start completely from scratch, it's often recommended to remove the entire build directory and reconfigure:
rm -rf build/
mkdir build && cd build
cmake ..
make
Using other generators like Ninja, Visual Studio, etc.:
For other generators (e.g., Ninja, or when generating projects for IDEs like Visual Studio), there isn't a universal make clean equivalent. For Ninja, you would use:
ninja -t clean
But for a completely clean start, regardless of the generator, removing the build directory is the most straightforward method:
rm -rf build/
Then recreate the build directory, reconfigure your project with CMake, and build again:
mkdir build && cd build
cmake .. # Add additional flags as necessary
cmake --build . # This command is generator-agnostic
CMake Build Command for Cleaning (Generator-Agnostic):
Starting from CMake 3.15, you can use the --build option with --target clean to perform a cleaning step in a generator-agnostic way. However, this still relies on the underlying build system's support for the "clean" target, and might behave similarly to make clean, i.e., not removing everything:
cmake --build . --target clean
Full Clean Build:
For a full, clean build (removing all artifacts including CMake's cache), simply delete the build directory and start over:
rm -rf build/ # Or the directory you're using for builds
mkdir build && cd build
cmake .. # Reconfigure from scratch
cmake --build . # Build the project
In summary, while CMake doesn't directly offer a clean command akin to make clean, you can achieve a full clean build by removing the build directory and reconfiguring the project. This ensures that no stale artifacts affect your build process.
If the compiler is unable to find nlohmann/json.hpp, it suggests an issue with how the library is being included or an issue with how your project's CMake setup handles the nlohmann/json library dependency. Here are several common reasons this might happen and how to address them:
1. Incorrect FetchContent Configuration
Ensure that your FetchContent configuration in the CMakeLists.txt file is correct and matches the instructions provided for using FetchContent with the nlohmann/json library. Here's a reminder of how it could look:
include(FetchContent)
FetchContent_Declare(
json
GIT_REPOSITORY https://github.com/nlohmann/json.git
GIT_TAG v3.10.5 # Use the version you need
)
FetchContent_MakeAvailable(json)
This approach automatically handles the population, configuration, and inclusion of the library in the build. Make sure you are using a recent enough version of CMake (version 3.14 or newer for FetchContent_MakeAvailable).
2. Target Linking
Ensure that you correctly link your target against the nlohmann_json::nlohmann_json target:
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} nlohmann_json::nlohmann_json)
3. Minimum CMake Version
Verify that the CMake version you're using supports FetchContent and FetchContent_MakeAvailable. Using a recent version of CMake (at least 3.14 or newer) is recommended, as FetchContent_MakeAvailable was introduced in 3.14. If you cannot upgrade CMake, you may need to use the longer form of FetchContent_Populate followed by add_subdirectory.
4. CMake Cache/Ancient Build Artifacts
Sometimes, CMake cache or old build artifacts might cause inconsistencies. Try clearing your build directory completely and rerun CMake from scratch:
rm -rf build/
mkdir -p build && cd build
cmake ..
cmake --build .
5. Check Your Include Statements
Although this seems basic, verify that your include statement in the C++ source file correctly references the header:
#include <nlohmann/json.hpp>
6. CMakeLists.txt Structure
Ensure that the FetchContent_Declare and associated commands are placed before the declaration of your target (add_executable or add_library) in your CMakeLists.txt. CMake processes commands in order, so FetchContent_MakeAvailable or its equivalent sequence must be invoked before defining targets that depend on the fetched content.
7. Check for Typos in CMakeLists.txt
A typo in CMakeLists.txt can lead to unexpected behavior. Double-check all specified paths, target names, and library names for errors.
Moving Forward
If you've gone through these steps and still face issues, consider isolating the problem:
- Try a minimal example that only fetches and includes
nlohmann/json to verify that the issue is with the library fetching and including.
- Verify that your system's network configuration allows you to fetch content from GitHub (e.g., via
git clone).
In complicated scenarios, the issue might not be immediately apparent. Isolating the problem, verifying configurations, and sometimes seeking specific help with detailed error messages and CMake output can be very useful.