一、介绍
本文将介绍一种以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 以上版本) - 州长在手 - 博客园
3301

被折叠的 条评论
为什么被折叠?



