json: Including nlohmann the badwrong way.

I want to use your library in a game. I’ve added proper code to find and link to it, but I also want to allow for the possibility somebody might want to compile the game and not know how to (or even just not want to) find/install nlohmnann.

So… instead of just dropping an include_directories I decided I’d try embedding your library as a submodule and just including your CMakeLists if a config module cannot be found. I am not entirely sure what nasty repercusions this could have but I figured it was better since it’s still using your logic to define the target.

The only problem is, in doing this I ran into a million errors due to includes or subdirectories not existing (being called from your CMakeLists). I tracked this down to CMake populating essentially all variables (and also using it when not otherwise explicitly specified, such as in

add_subdirectory(test)

with my project folder instead of yours. I then realized I could use CMAKE_CURRENT_LIST_DIR instead of CMAKE_CURRENT_SOURCE_DIR and PROJECT_SOURCE_DIR and it will work fine.

Since I’d rather not modify your files (Ideally I’d like to be able to easily update my included version from your releases)… do you think it might be possible to support what I’m doing by comparing CMAKE_CURRENT_LIST_DIR and CMAKE_CURRENT_SOURCE_DIR and using the former if they’re not equal?

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 20 (14 by maintainers)

Most upvoted comments

include() is for including cmake module files, which a CMakeLists.txt is not. Use add_subdirectory().

I looked at the project’s CMakeLists.txt, and I don’t see anything which is unfriendly to add_subdirectory(). A quick test showed that it indeed works to include nlohmann_json as a subdirectory, no changes needed.

You may want to turn off BUILD_TESTING when you add the subdirectory, though, unless you want to build all of the tests:

project(MyProject)

# ...

set(OLD_BUILD_TESTING "${BUILD_TESTING}")
set(BUILD_TESTING FALSE)
add_subdirectory(external/nlohmann_json)
set(BUILD_TESTING "${OLD_BUILD_TESTING}")

# ...

add_executable(my_executable ...)
target_link_libraries(my_executable PRIVATE nlohmann_json::nlohmann_json)