iT邦幫忙

2026 iThome 鐵人賽

DAY 4
0
Software Development

C++ 套件管理器求生指南 Conan vs Vcpkg系列 第 4

D04: Visual Studio 搭配 Conan 套件管理器

  • 分享至 

  • xImage
  •  

上一篇 D03 我們用的是 Conan + CMake 的組合。但現實世界裡,不是每個專案都用 CMake。

接下來幾天,來看看 Conan 怎麼接上另外三種常見的建置系統:

  1. Visual Studio (MSBuild) ← 今天
  2. Xcode
  3. Makefiles

今天先從 Visual Studio 開始。

這篇範例使用的工具版本是 Visual Studio 2022 以及 Conan 2.32

步驟一:建立 Visual Studio 專案

首先,請開啟 Visual Studio 建立一個基本的 C++ 專案。

建立後,往專案根目錄添加一個名為 conanfile.txt 的文字檔案,作為 Conan 的設定入口。

目錄結構如下:

hello-conan-msvs/
├── conanfile.txt
├── hello-conan.sln
├── hello-conan.vcxproj
└── main.cpp

步驟二:撰寫 conanfile.txt

開啟 conanfile.txt ,填入以下內容。

[requires]
fmt/12.2.0
nlohmann_json/3.12.0

[generators]
MSBuildDeps
MSBuildToolchain

[layout]
vs_layout

內容的寫法跟昨天幾乎一樣。

[requires] 區塊裡面是我們想要導入的函式庫+版本號碼,一個庫一行。

重點是 [generators] 區塊,這裡要要指定 MSBuildDeps + MSBuildToolchain ,明確告知 Conan 接下來準備跟 Visual Studio 對接。-

最後的 [layout] 區塊則是設定目錄結構。使用 vs_layout 讓產生的所有檔案自動集中管理在進 conan/ 子目錄下,保持專案目錄乾淨。

步驟三:執行 Conan Install 安裝套件

接下來我們就可以來安裝套件囉!

開啟命令列並切換到專案的根目錄。由於 Visual Studio 預設有Debug/Release兩種組態,而且兩種二進位檔互不相容,所以 conan install 要打兩次:

conan install . --build=missing -s build_type=Release
conan install . --build=missing -s build_type=Debug

跑完之後 conan/ 底下會多出一堆 .props

conan/
├── conandeps.props
├── conan_fmt.props
├── conan_fmt__fmt_release_x64.props
├── conan_fmt__fmt_vars_release_x64.props
├── conan_nlohmann_json_release_x64.props
├── conan_nlohmann_json_debug_x64.props
├── ...
├── conantoolchain_release_x64.props
├── conantoolchain_debug_x64.props
└── conantoolchain.props

別擔心,我們只需要關心兩個核心檔案:conandeps.props 與 conantoolchain.props。

步驟四:在 Visual Studio 中匯入屬性表

現在來到最關鍵的一步了!

我們透過 Visual Studio 的 GUI 界面來設定:
點擊上方功能表:檢視 > 其他視窗 > 屬性管理員 (Property Manager)。
(View -> Others -> Property Manager)

在屬性管理員視窗中,找到你的專案名稱,在專案上按右鍵選擇加入現有屬性表 (Add Existing Property Sheet...)

MSVC 2022 Add Existing Property Sheet

進入 conan/ 子目錄,選擇 conandeps.props
重複上一動作,選擇 conantoolchain.props

這樣子就成功把 Conan 和 Visual Studio 連結起來囉。

步驟五:編譯專案並執行!

現在 main.cpp 裡面已經可以直接使用 fmt 以及 nlohmann JSON 函式庫了:

#include <fmt/base.h>
#include <nlohmann/json.hpp>

int main() {
    nlohmann::json j = {
        {"name", "Conan"},
        {"language", "Python"},
        {"stars", 9000}
    };

    fmt::print("Hello, {}!\n", j["name"].get<std::string>());
    fmt::print("{}\n", j.dump(2));
    return 0;
}

順利的話按下 F5 就會進行編譯與執行!完全不需要手動設定繁鎖的 Include/Link 目錄了。


上一篇
D03: Conan 套件管理第一步:Hello conanfile.txt
下一篇
D05: Xcode 搭配 Conan 套件管理器
系列文
C++ 套件管理器求生指南 Conan vs Vcpkg6
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言