跳到主要内容

使用 MSBuild 在 Visual Studio 中安装和使用包

本教程展示如何创建一个使用 fmt 库的 C++ “Hello World”程序,使用 MSBuild、kmpkg 和 Visual Studio 来安装依赖、配置项目、构建和运行应用。

前提条件

1 - 设置 kmpkg

  1. 克隆仓库
git clone https://github.com/kumose/kmpkg.git

kmpkg 注册表包含 2000+ 个开源库,通过 CI 验证可协同工作。仓库本身不含源码,只提供构建和安装所需的配方和元数据。

  1. 运行引导脚本
cd kmpkg && bootstrap-kmpkg.bat

脚本会检查前置条件并下载 kmpkg 可执行文件。至此,kmpkg 已可用。

  1. 与 Visual Studio MSBuild 集成
.\kmpkg.exe integrate install

输出:

All MSBuild C++ projects can now #include any installed libraries. Linking will be handled automatically. Installing new libraries will make them instantly available.

2 - 设置 Visual Studio 项目

  1. 创建项目
  • 使用 “Console Application” 模板新建项目。
  • 命名为 helloworld
  • 勾选 “Place solution and project in the same directory”。
  • 点击 “Create”。
  1. 配置 KMPKG_ROOT 环境变量

打开 Visual Studio 内置 Developer PowerShell:

$env:KMPKG_ROOT = "C:\path\to\kmpkg"
$env:PATH = "$env:KMPKG_ROOT;$env:PATH"
  1. 创建 manifest 并添加依赖
kmpkg new --application
kmpkg add port fmt

kmpkg.json 应包含:

{
"dependencies": [
"fmt"
]
}

3 - 设置项目源文件

修改 helloworld.cpp

#include <fmt/core.h>

int main()
{
fmt::print("Hello World!\n");
return 0;
}

4 - 启用 Manifest 模式

  1. 打开 Project > Properties
  2. 导航到 Configuration Properties > kmpkg,设置 Use kmpkg ManifestYes

5 - 构建并运行项目

  1. 使用 Build > Build Solution 构建项目。
  2. MSBuild 会在预构建步骤安装 manifest 依赖,安装目录在 kmpkg_installed
  3. 运行可执行文件,应显示:
Hello World!

下一步

了解更多关于 kmpkg.json 和 MSBuild 集成: