現代cmake 從github引入三方庫,使用FetchContent ( 3.14 以上版本)


使用FetchContent的步驟總結起來就是:

  • 在cmake文件寫入  include(FetchContent) ,具體看完整實例
  • 使用FetchContent_Declare(三方庫) 獲取項目。可以是一個URL也可以是一個Git倉庫。
  • 使用FetchContent_MakeAvailable(三方庫) 獲取我們需要庫,然后引入項目。
  • 使用 target_link_libraries(項目名PRIVATE 三方庫::三方庫)

看例子! 這個例子 https://github.com/nlohmann/json

第一步:

  在 CMakeLists.txt 文件寫入 include(FetchContent)

第二步:

  # FetchContent_Declare

  FetchContent_Declare(json
        GIT_REPOSITORY https://gitee.com/slamist/json.git   #gitee加速
        GIT_TAG v3.7.3)

第三部

  # FetchContent_MakeAvailable

  FetchContent_MakeAvailable(json)

第四步

  # target_link_libraries

  target_link_libraries(項目名字PRIVATE nlohmann_json::nlohmann_json)

 

看一下完整的cmake

cmake_minimum_required(VERSION 3.17)
project(mjson)

set(CMAKE_CXX_STANDARD 14)

file(GLOB SOURCES_AND_HEADERS "*.cpp" "include/*.h")

add_executable(mjson main.cpp ${SOURCES_AND_HEADERS})
target_include_directories(${PROJECT_NAME}
        PUBLIC ${PROJECT_SOURCE_DIR}/include
        )
include(FetchContent)

FetchContent_Declare(json
        GIT_REPOSITORY https://gitee.com/slamist/json.git
        GIT_TAG v3.7.3)
FetchContent_MakeAvailable(json)

target_link_libraries(mjson PRIVATE nlohmann_json::nlohmann_json)

FetchContent_Declare(spdlog
        GIT_REPOSITORY https://gitee.com/mai12/spdlog.git
        GIT_TAG v1.4.1)
FetchContent_MakeAvailable(spdlog)
target_link_libraries(mjson PRIVATE spdlog::spdlog)

下面是如何使用

//
// Created by ct on 2020/9/3.
//

#include <iostream>
#include <spdlog/spdlog.h>
#include <nlohmann/json.hpp>

using json = nlohmann::json;
int runner(){
    // create JSON values
    json object = {{"one", 1}, {"two", 2}};
    json null;

    // print values
    std::cout << object << '\n';
    std::cout << null << '\n';

    // add values
    auto res1 = object.emplace("three", 3);
    null.emplace("A", "a");
    null.emplace("B", "b");

    // the following call will not add an object, because there is already
    // a value stored at key "B"
    auto res2 = null.emplace("B", "c");

    // print values
    std::cout << object << '\n';
    std::cout << *res1.first << " " << std::boolalpha << res1.second << '\n';

    std::cout << null << '\n';
    std::cout << *res2.first << " " << std::boolalpha << res2.second << '\n';

    spdlog::info("i love c++");
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM