4

I am using the following JSON parser: https://github.com/nlohmann/json

Following is the steps I followed to build :

 2074  git clone https://github.com/nlohmann/json.git
 2075  git branch
 2076  ls
 2077  cd json/
 2078  git branch
 2079  git pull
 2080  ls
 2081  vi CODE_OF_CONDUCT.md 
 2082  mkdir build
 2083  cd build/
 2084  ls
 2085  cmake ..
 2086  cmake --build .
 2087  ctest --output-on-failure

The unit tests pass. I do not see the library being built, as the documentation mentions.

I am trying to build a simple hello world program for the parser. Here is the code:

#include <nlohmann/json.hpp>
#include<string.h>
// for convenience
using json = nlohmann::json;

int
main(int argc, char *argv[])
{
    std::ifstream ifs("test.json");
    json jf = json::parse(ifs);
     return 0;
}

And the CMake file:

# CMakeLists.txt
cmake_minimum_required(VERSION 3.10)

# set the project name
project(my_json CXX)
find_package(nlohmann_json 3.2.0 REQUIRED)

However, CMake cannot find the package nlohmann_json.

Please suggest how to build this example. I am planning to use the external library method to build this code.

Pedro Mutter
  • 1,178
  • 1
  • 13
  • 18

1 Answers1

3

Package Approach

The default behavior of find_package is expecting to find the package installed on your system.

If you have a simple local clone, then you should provide a Find***.cmake file in your module path, which matches the module name.

For example, make a file called Findnlohmann_json.cmake with some contents like this:

if( TARGET nlohmann_json )
  return()
endif()

if(NOT NLOHMANNJSON_ROOT)
  set(NLOHMANNJSON_ROOT "${PROJECT_SOURCE_DIR}/lib/json")
endif()

add_library( nlohmann_json INTERFACE )
target_include_directories(
  nlohmann_json
  INTERFACE
    ${NLOHMANNJSON_ROOT}/include
)

See https://cmake.org/cmake/help/latest/command/find_package.html#search-procedure for more info.

Local Source Approach

That said, if you are keeping the library in your source tree, you might find it easier to simply call add_subdirectory from your project's CMakeLists.txt:

project(my_json CXX)
add_subdirectory( lib/nlohmann_json )

//...
target_link_libraries( myApp PRIVATE nlohmann_json )

Be aware that not all libraries are ready to be included in this fashion

yano
  • 4,095
  • 3
  • 35
  • 68