模組化開發-用 CMake + VCpkg 封裝並重用 C++ 函式庫

專案結構 (同樣維持模組化)

Code

project-root/
│── CMakeLists.txt
│── vcpkg.json              # vcpkg 套件描述
│── libs/
│   └── image_processing/
│       ├── include/
│       │   └── image_processing.hpp
│       ├── src/
│       │   └── image_processing.cpp
│       └── CMakeLists.txt
│── apps/
│   ├── cli_tool_A/
│   │   └── CMakeLists.txt
│   └── cli_tool_B/
│       └── CMakeLists.txt

🛠️ libs/image_processing/CMakeLists.txt

cmake

cmake_minimum_required(VERSION 3.15)
project(image_processing LANGUAGES CXX)
add_library(image_processing src/image_processing.cpp)
target_include_directories(image_processing PUBLIC include)
target_compile_features(image_processing PUBLIC cxx_std_17)

🛠️ 頂層 CMakeLists.txt

cmake

cmake_minimum_required(VERSION 3.15)
project(ModularCpp LANGUAGES CXX)
# 引入子模組
add_subdirectory(libs/image_processing)
add_subdirectory(apps/cli_tool_A)
add_subdirectory(apps/cli_tool_B)

🛠️ apps/cli_tool_A/CMakeLists.txt

cmake

cmake_minimum_required(VERSION 3.15)
project(cli_tool_A LANGUAGES CXX)
add_executable(cli_tool_A main.cpp)
target_link_libraries(cli_tool_A PRIVATE image_processing)

📦 vcpkg 套件描述 (vcpkg.json)

json

{
  "name": "modular-cpp",
  "version-string": "1.0.0",
  "dependencies": [
    "opencv4",
    "fmt"
  ]
}

🚀 使用方式

  1. 安裝 vcpkg 並整合 CMake
    bash
    git clone https://github.com/microsoft/vcpkg.git
    ./vcpkg/bootstrap-vcpkg.sh
    
  2. 安裝依賴
    bash
    ./vcpkg/vcpkg install
    
  3. CMake 配置
    bash
    cmake -B build -S . -DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake
    cmake --build build
    

📊 Conan vs vcpkg 對照表

特性 Conan vcpkg
跨平台 Windows/Linux/macOS Windows/Linux/macOS
套件來源 公開/私有 Conan server 官方 registry + GitHub
版本控制 強,支援多版本並行 弱,通常只有最新版本
企業私有倉庫 支援 不支援 (需 fork registry)
整合度 靈活,CI/CD 常用 微軟官方,VS/VSCode 整合佳
使用體驗 類似 pip install 類似 apt-get install

🎯 建議

  • 如果你要像 Python whl 一樣方便封裝、分發,甚至建私有倉庫 → Conan 更適合。
  • 如果你主要在 Windows/VSCode/Visual Studio 開發,並且依賴多是常見開源庫 → vcpkg 更方便。

Also See

File8FileLast Modified
模組化開發-VCpkg工具模組化開發-VCpkg工具1:22 AM - December 07, 2025
查詢目前vcpkg registry所在路徑查詢目前vcpkg registry所在路徑1:22 AM - December 07, 2025
本地 `src` vs. `vcpkg_from_git`本地 src vs. vcpkg_from_git1:22 AM - December 07, 2025
如何產生 git-tree如何產生 git-tree1:22 AM - December 07, 2025
使用 vcpkg x-add-version 搭配 Git 或目錄結構工具,自動建立與維護本地 vcpkg registry使用 vcpkg x-add-version 搭配 Git 或目錄結構工具,自動建立與維護本地 vcpkg registry1:22 AM - December 07, 2025
vcpkg-local-how-tovcpkg-local-how-to1:22 AM - December 07, 2025
vcpkg_checkervcpkg_checker1:22 AM - December 07, 2025
vcpkg 指令總覽表vcpkg 指令總覽表1:22 AM - December 07, 2025