You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CMake加载nlohmann/json.hpp失败:头文件未找到致命错误

解决nlohmann/json在CMake中引入失败的问题

问题原因

  • 你注释掉了nlohmann/json的FetchContent初始化代码,即便_deps目录有文件,CMake也不会自动将其纳入构建流程
  • nlohmann/json是纯头文件库,无需用target_link_libraries做链接操作,但需要正确关联它的头文件路径

修正方案

1. 启用并配置FetchContent加载nlohmann/json

取消CMakeLists.txt中关于json的注释,建议指定稳定版本标签避免兼容性问题。

2. 正确关联库到编译目标

nlohmann/json提供了官方CMake目标nlohmann_json::nlohmann_json,通过target_link_libraries关联该目标,CMake会自动处理头文件路径配置。

3. 使用标准的头文件引入路径

在代码中直接使用#include <nlohmann/json.hpp>即可。


修正后的CMakeLists.txt

cmake_minimum_required(VERSION 3.24)
project(main)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build)

# 加载nlohmann/json库
include(FetchContent)
FetchContent_Declare(
  json
  GIT_REPOSITORY https://github.com/nlohmann/json
  GIT_TAG v3.11.2 # 指定稳定版本,可选但推荐
)
FetchContent_MakeAvailable(json)

# 加载fmt库
FetchContent_Declare(fmt
    GIT_REPOSITORY https://github.com/fmtlib/fmt
    GIT_TAG 9.0.0
)
FetchContent_MakeAvailable(fmt)

add_executable(main main.cpp)
# 关联依赖库,PRIVATE指定依赖仅用于当前目标
target_link_libraries(main PRIVATE nlohmann_json::nlohmann_json fmt)

修正后的main.cpp

#include <iostream>
#include <fmt/core.h>
#include <nlohmann/json.hpp>

// 简化json类型使用
using json = nlohmann::json;

int main(){
    fmt::print("Hello, world!\n");
    
    // 测试json功能
    json test_json = {
        {"username", "dsj-23"},
        {"score", 95}
    };
    fmt::print("测试JSON内容:\n{}\n", test_json.dump(4));
    
    return 0;
}

额外说明:

  • 无需手动设置CMAKE_CXX_FLAGS "-std=c++17",set(CMAKE_CXX_STANDARD 17)已经会自动添加对应编译标准
  • 使用PRIVATE关键字限定依赖范围,是CMake的最佳实践,避免不必要的依赖传递

内容的提问来源于stack exchange,提问作者dsj-23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:01:07