CLion环境下引入Modern C++ JSON库失败的技术咨询
Hey there! Let's get that nlohmann/json library working in your school project—this is a super common hiccup when setting up modern C++ libraries, so we'll sort it out quickly.
First: Double-Check Your CMake Setup
The most likely culprit is that CMake isn't properly aware of where the nlohmann/json headers live. Here are two reliable ways to fix this:
Option 1: Use FetchContent (Modern C++ Recommended)
This lets CMake automatically download and configure the library for you, no manual file copying needed. Add this code to your CMakeLists.txt:
include(FetchContent) FetchContent_Declare( json GIT_REPOSITORY https://github.com/nlohmann/json.git GIT_TAG v3.11.2 # Swap this for the latest stable tag if needed ) FetchContent_MakeAvailable(json) # Link the library to your executable add_executable(your_project_name main.cpp) # Replace with your actual executable name target_link_libraries(your_project_name PRIVATE nlohmann_json::nlohmann_json)
After adding this, click the "Reload CMake Project" button in CLion's top-right corner to apply the changes.
Option 2: Manual Single-Header Setup
If you downloaded the single-header version of nlohmann/json (the json.hpp file inside the single_include/nlohmann folder):
- Create a
libsfolder in your project root, then place the entirenlohmannfolder (containingjson.hpp) inside it. - Add this line to your
CMakeLists.txtto tell CMake where to find the headers:
include_directories(${PROJECT_SOURCE_DIR}/libs)
Then in your .cpp file, include the library like this:
#include "nlohmann/json.hpp"
Second: Verify Your Include Statement
Make sure you're using the right syntax for your setup:
- If you used FetchContent or installed the library system-wide,
#include <nlohmann/json.hpp>should work. - If you're using the manual single-header setup, stick with double quotes (
") instead of angle brackets (<) unless you've added the path to your system's include directories.
Third: Clear CLion's CMake Cache
Sometimes CLion holds onto old cache data that causes issues. Try either:
- Clicking
File > Reload CMake Project - Deleting the
cmake-build-debug/cmake-build-releasefolders and re-running the build
That should resolve the "fatal error: nlohmann..." message. If you're still stuck, double-check that the library path in CMake matches where you actually placed the files—small typos here are easy to miss!
内容的提问来源于stack exchange,提问作者Etienne Berube

