C++包管理器vcpkg的使用
文档
https://learn.microsoft.com/zh-cn/vcpkg/get_started/get-started?pivots=shell-bash
搜索想要的包
https://vcpkg.io/en/packages?query=
安装vcpkg
1、获取源码
git clone https://github.com/microsoft/vcpkg.git
cd vcpkg && ./bootstrap-vcpkg.sh
2、配置 VCPKG_ROOT 环境变量
# cat ~/.bash_profile
# vcpkg
export VCPKG_ROOT=/usr/local/vcpkg
export PATH=$VCPKG_ROOT:$PATH
3、安装检查
$ vcpkg --version
vcpkg package management program version 2025-06-02-145689e84b7637525510e2c9b4ee603fda046b56See LICENSE.txt for license information.
安装ninja
https://ninja-build.org/
下载对应平台的包,解压即可
ninja --version
1.12.1
使用
新建一个项目
# 创建项目目录
mkdir helloworld && cd helloworld# 创建清单文件
vcpkg new --application# 添加 fmt 依赖项
vcpkg add port fmt
创建必要的文件
创建文件 CMakePresets.json
{"version": 2,"configurePresets": [{"name": "vcpkg","generator": "Ninja","binaryDir": "${sourceDir}/build","cacheVariables": {"CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"}}]
}
CMakeUserPresets.json
{"version": 2,"configurePresets": [{"name": "default","inherits": "vcpkg","environment": {}}]
}
创建文件 CMakeLists.txt
cmake_minimum_required(VERSION 3.10)project(HelloWorld)find_package(fmt CONFIG REQUIRED)add_executable(HelloWorld helloworld.cpp)target_link_libraries(HelloWorld PRIVATE fmt::fmt)
创建文件 helloworld.cpp
#include <fmt/core.h>int main()
{fmt::print("Hello World!\n");return 0;
}
编译并运行项目
# 使用 CMake 配置生成
cmake --preset=default# 生成项目
cmake --build build# 运行应用程序
./build/HelloWorldHello World!
为了便捷,可以创建文件 Makefile
.PONEY: run
run:cmake --build build && ./build/HelloWorld
以后只要运行如下命令即可
make run
最终的项目文件
$ tree
.
├── CMakeLists.txt
├── CMakePresets.json
├── CMakeUserPresets.json
├── Makefile
├── helloworld.cpp
├── vcpkg-configuration.json
└── vcpkg.json