现代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;
}

 

posted @ 2020-09-04 09:30  州长在手  阅读(8095)  评论(0编辑  收藏  举报