Clion vcpkg使用 Clion下vcpkg的使用详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Clion vcpkg使用 Clion下vcpkg的使用详解

许非   2021-04-13 我要评论
想了解Clion下vcpkg的使用详解的相关内容吗,许非在本文为您仔细讲解Clion vcpkg使用的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Clion,vcpkg使用,Clion,vcpkg,下面大家一起来学习吧。

环境

ubuntu 20+
clion 2021.1

背景

在Linux下,每次新创建1个项目,可能会使用一些第三方库,比如:

  • toml解析
  • spdlog日志

难道每次都要我去重新下载源码,然后编译,在配置CMake?太麻烦了吧,看看别人前端,需要一个包只用执行 npm install axio 就行了,好羡慕。

刚好,前段时间在windows下使用了一把vcpkg,目前vcpkg作为c++的包管理工具,已经相对成熟了,很多著名的开源组件都对vcpkg进行了支持。

于是,我们在Ubuntu 20 下 通过Clion来试试可不可以呢?

vcpkg

先来安装一下 Github

# Debian, Ubuntu 要额外执行
$ sudo apt-get update
$ sudo apt-get install build-essential tar curl zip unzip

# CentOS 要额外执行
$ sudo yum install centos-release-scl
$ sudo yum install devtoolset-7
$ scl enable devtoolset-7 bash
$ git clone https://github.com/microsoft/vcpkg
$ .\vcpkg\bootstrap-vcpkg.sh
$ vim ~/.bashrc
# 加入vcpkg的路径到环境变量
export PATH=/home/xmcy0011/data/vcpkg:$PATH
$ source ~/.bashrc # 立即生效
$ vcpkg help # 不报错,则成功

使用方法,记住2个命令即可 searchinstall

$ vcpkg search toml11 # 搜索c++包
$ vcpkg install tmol11 # 安装c++包,并且进行本地编译,后面就可以直接在clion中通过find_packge()使用。

如何在Clion中使用

创建一个项目

在这里插入图片描述

配置Clion,使用vcpkg

注意:这个配置是针对项目级别,故每个项目都需要配置。

  • Open the Toolchains settings (File > Settings on Windows and Linux, CLion > Preferences on macOS),
  • and go to the CMake settings (Build, Execution, Deployment > CMake)
  • Finally, in CMake options, add the following line
-DCMAKE_TOOLCHAIN_FILE=[vcpkg root]/scripts/buildsystems/vcpkg.cmake

在这里插入图片描述

编辑CMakeList.txt

因为之前已经通过:

$ vcpkg install tmol11
The package toml11:x64-linux provides CMake targets:

    find_package(toml11 CONFIG REQUIRED)
    target_link_libraries(main PRIVATE toml11::toml11)

安装了toml解析的包,安装成功后会打印使用方法如find_packge(…),target_link_libraries(…),我们把它拷贝到CMakeList.txt中使用:

cmake_minimum_required(VERSION 3.0)
project(test_vcpkg_in_clion)

set(CMAKE_CXX_STANDARD 14)

# 这里使用toml11来解析toml文件
find_package(toml11 REQUIRED)
if (toml11_FOUND)
    message("find toml11=${toml11_VERSION}")
endif ()

add_executable(test_vcpkg_in_clion main.cpp)
# 通过静态库的方式使用toml11
target_link_libraries(test_vcpkg_in_clion PRIVATE toml11::toml11)

别忘记了,点击Reload changes,重新生成项目哦。

在这里插入图片描述

创建一个toml测试文件

在cmake-build-debug目录下面创建一个example.tmo文件,内容如下:

[server]
ip = "127.0.0.1"

如何使用安装的toml11库?

使用的话,就很简单了,直接include即可。
main.cpp

#include <iostream>
// 这里的路径是什么,见每个库的github说明
// 比如vcpkg install spdlog,使用方法是:#include "spdlog/spdlog.h"
#include "toml.hpp"  

int main() {
    auto data = toml::parse("example.toml");
    auto &server = toml::find(data, "server");
    std::string ip = toml::find<std::string>(server, "ip");

    std::cout << "Hello, World!" << ip << std::endl;
    return 0;
}

编译运行

在这里插入图片描述
在这里插入图片描述

我们看到,很快的都实现了一个toml的文件解析,是不是很方便呢?

最后,我们来用nm(动态库就是ldd)验证一下:

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们