1. 程式人生 > 實用技巧 >Linux下配置C++操作json檔案

Linux下配置C++操作json檔案

nlohmann-json是一個用C++操作json檔案的庫,功能非常強大。本文記錄下如何在linux下用vcpkg安裝nlohmann-json並用CLion呼叫。

  1. 安裝vcpkg
    • 克隆vcpkg庫
      $ git clone https://github.com/microsoft/vcpkg
    • 執行bootstrap-vcpkg.sh檔案
      $ ./vcpkg/bootstrap-vcpkg.sh
      若在執行過程中下載cmake太慢,可去kitware自行下載對應的版本並放到vcpkg/downloads/資料夾下,然後重新執行bootstrap-vcpkg.sh。如在我的系統下,執行bootstrap-vcpkg.sh
      過程中下載了一部分cmake的安裝包,安裝包名稱為cmake-3.18.4-Linux-x86_64.tar.gz.part
  2. 安裝nlohmann-json
    $ ./vcpkg/vcpkg install nlohmann-json
    如果出現下載錯誤(對應的github issue),可自行下載nlohmann-json的安裝包,並解壓到[vcpkg root]/downloads裡([vcpkg root]根據實際情況修改),然後重新執行上述命令,如果安裝成功會出現:
Total elapsed time: 4.86 s

The package nlohmann-json:x64-linux provides CMake targets:

    find_package(nlohmann_json CONFIG REQUIRED)
    target_link_libraries(main PRIVATE nlohmann_json nlohmann_json::nlohmann_json)
  1. 配置CLion
    依次點選File->Setting->Build, Execution, Deployment->Cmake,在CMake options中新增:
    -DCMAKE_TOOLCHAIN_FILE=[vcpkg root]/scripts/buildsystems/vcpkg.cmake
    [vcpkg root]根據實際情況修改)
    最後在CMakeLists.txt中新增以下兩行:
find_package(nlohmann_json CONFIG REQUIRED)
target_link_libraries(main PRIVATE nlohmann_json nlohmann_json::nlohmann_json)

其中,mainPRIVATE根據實際情況修改。