CMake之引入git项目,使用FetchContent ( 3.14 以上版本)

一、介绍

本文将介绍一种以git源码的方式引入第三方库的方法

步骤:

 1. 在cmake文件写入  include(FetchContent) ,具体看完整实例.
 2. 使用FetchContent_Declare(三方库) 获取项目。可以是一个URL也可以是一个Git仓库。
 3. 使用FetchContent_MakeAvailable(三方库) 获取我们需要库,然后引入项目。
 4. 使用 target_link_libraries(项目名PRIVATE 三方库::三方库)

 二、实例

CMakeList.txt

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)

set(SPDLOG_GIT_TAG  v1.4.1)  # 指定版本
set(SPDLOG_GIT_URL  https://github.com/gabime/spdlog.git)  # 指定git仓库地址

FetchContent_Declare(
  spdlog
  GIT_REPOSITORY    ${SPDLOG_GIT_URL}
  GIT_TAG           ${SPDLOG_GIT_TAG}
)

FetchContent_MakeAvailable(spdlog)

target_link_libraries(mjson PRIVATE spdlog::spdlog)

main.cpp

//
// 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;
}

参考:

FetchContent — CMake 3.25.1 Documentation

现代cmake 从github引入三方库,使用FetchContent ( 3.14 以上版本) - 州长在手 - 博客园 

cmake以源码的方式引入第三方项目 - mohist - 博客园 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值