cmakenlohmann-json

Setting (nlohmann::json) options for CMake projects added with find_package


I am using the excellent nlohmann::json library. I can see that it has an option for disabling implicit conversion which is recommended.

First I tried to set this option via:

set(JSON_ImplicitConversions OFF)
find_package(nlohmann_json 3.10.3 REQUIRED)

But that did not seem to have any effect. I then tried using fetch_content:

set(JSON_ImplicitConversions OFF)
FetchContent_Declare(json
    GIT_REPOSITORY https://github.com/nlohmann/json
    GIT_TAG v3.11.3
)
FetchContent_MakeAvailable(json)

And this gave the required effect. I much prefer the find_package. Am I using it wrong? Is it not possible to set options in this way with find_package?


Solution

  • JSON_ImplicitConversions is the option used when build the library. find_package locates the library which is already built and installed. So setting build options for find_package is useless.

    That build option affects on the setting macro JSON_USE_IMPLICIT_CONVERSIONS for the consumer of the library. You may set this macro manually for the imported target, created by find_package:

    find_package(nlohmann_json 3.10.3 REQUIRED)
    
    # For the case the macro is already set in the target's compile definitions
    # we need to remove that setting. Otherwise it will conflict with our one.
    
    # Extract current value of the property (as list)
    get_target_property(prop_value nlohmann_json::nlohmann_json INTERFACE_COMPILE_DEFINITIONS)
    # Remove unneeded elements
    list(FILTER prop_value EXCLUDE REGEX "JSON_USE_IMPLICIT_CONVERSIONS")
    # Put resulting list back to the property
    set_property(TARGET nlohmann_json::nlohmann_json PROPERTY INTERFACE_COMPILE_DEFINITIONS ${prop_value})
     
    target_compile_definitions(nlohmann_json::nlohmann_json INTERFACE
      JSON_USE_IMPLICIT_CONVERSIONS=0
    )