Home > Enterprise >  Unabled to load lohmann/json.hpp using CMake - getting fatal error: 'nlohmann/json.hpp' fi
Unabled to load lohmann/json.hpp using CMake - getting fatal error: 'nlohmann/json.hpp' fi

Time:11-20

I have the following main.cpp, very simple script, trying to re-produce the problem and isolate to it's most basic.

#include<iostream>

#include<fmt/core.h>

// #include "json/json.hpp"
// #include <json/json.hpp>
// #include <nlohmann/json.hpp>
// #include "json.hpp"
// #include "nlohmann/json.hpp"

int main(){
    fmt::print("Hello, world!\n");
    return 0;
}

The commented out include statements are all of the paths I have tried to get this into my program.

My CMakeLists.txt file looks like this

cmake_minimum_required(VERSION 3.24)
project(main)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-std=c  17")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build)

# include(FetchContent)
# FetchContent_Declare(
#   json
#   GIT_REPOSITORY https://github.com/nlohmann/json
# )
# FetchContent_MakeAvailable(json)

include(FetchContent)
FetchContent_Declare(fmt
    GIT_REPOSITORY https://github.com/fmtlib/fmt
    GIT_TAG 9.0.0
)
FetchContent_MakeAvailable(fmt)

add_executable(main main.cpp)
# target_link_libraries(main json)
target_link_libraries(main fmt)

I've commented out the json part since it's not working obviously, I can also json-src and json-build in my _deps folder so I know for a fact that it is being downloaded into my local machine.

After running cmake CMakeLists.txt and make and then running the executable I get the error in the title 'nlohmann/json.hpp' file not found

Any help would be appreciated.

Tried to reproduce the example with another popular C package which worked fine. Tried changing the include statements to see if maybe I had something wrong since I don't fully understand all the nuance with CMake and am quite new to it.

CodePudding user response:

You can either specifically use the interface target already included in the nlohmann library, which will automatically populate the correct include path for you, with:

target_link_libraries(main nlohmann_json::nlohmann_json)

Or you would need to specifically include the include path yourself:

include_directories(${json_SOURCE_DIR}/include)

With either way, you will be able to use #include <nlohmann/json.hpp> in your source.

  • Related