I have the following directory structure for my cmake project (it is a minimally working example for the sake of this post). I am using nlohmann_json
library for my project. I can create jsonExample1
and can successfully run jsonExample1.exe
but having difficulty building jsonExample2
as Cmake complains about not being able to find #include <nlohmann/json.hpp>
. Both jsonExample1
and jsonExample2
have the same file content for their source files.
Could someone kindly let me know what I am missing that is preventing jsonExample2
from being built? I want to be able to build jsonExample2
from the top level CMakeLists.txt
(is this not recommended? In my actual project, I will be builing a library that uses nlohmann
for the main executable of the project).
myapp
│
│ CMakeLists.txt
│
├───example
│ CMakeLists.txt
│ json.example.cpp
│
├───external
│ └───nlohmann_json
│ CMakeLists.txt
│
└───src
json.example.cpp
The content of the top-level CMakeLists.txt
is as follows:
cmake_minimum_required(VERSION 3.24)
project(my-app VERSION 1.0.0)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
add_subdirectory(external/nlohmann_json)
add_subdirectory(example) # it contains jsonExample1
add_executable(jsonExample2)
set_target_properties(jsonExample2 PROPERTIES LINKER_LANGUAGE CXX)
target_sources(jsonExample2 PRIVATE src/json.example.cpp)
target_link_directories(jsonExample2 PRIVATE nlohmann_json::nlohmann_json)
The content of the top-level /external/nlohmann_json/CMakeLists.txt
is as follows:
cmake_minimum_required(VERSION 3.24)
project(libjson VERSION 1.0.0)
set(CMAKE_CXX_STANDARD 20)
include(FetchContent)
FetchContent_Declare(nlohmann_json GIT_REPOSITORY https://github.com/nlohmann/json.git)
FetchContent_MakeAvailable(nlohmann_json)
The content of the top-level /example/CMakeLists.txt
is as follows:
cmake_minimum_required(VERSION 3.24)
project(projExamples VERSION 1.0.0)
set(CMAKE_CXX_STANDARD 20)
add_executable(jsonExample1 json.example.cpp)
target_link_libraries(jsonExample1 PRIVATE nlohmann_json::nlohmann_json)
The content of src/json.example.cpp
and example/jsonExample1.cpp
are the same and is as follows.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;
std::string s = j.dump();
std::cout << s;
return 0;
}