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

專案結構範例

Code

project-root/
│── CMakeLists.txt          # 頂層
│── conanfile.py            # Conan 套件描述
│── 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)
# 設定 C++ 標準
target_compile_features(image_processing PUBLIC cxx_std_17)
# 如果有第三方依賴,可以用 find_package 或 Conan/vcpkg 提供

🛠️ 頂層 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)

📦 Conan 套件描述 (conanfile.py)

python

from conan import ConanFile
from conan.tools.cmake import CMake, cmake_layout
class ImageProcessingConan(ConanFile):
    name = "image_processing"
    version = "1.0.0"
    license = "MIT"
    author = "Your Name"
    url = "https://github.com/yourrepo/image_processing"
    description = "Reusable image processing library"
    topics = ("image", "processing", "cpp", "modular")
    settings = "os", "compiler", "build_type", "arch"
    generators = "CMakeDeps", "CMakeToolchain"
    def layout(self):
        cmake_layout(self)
    def requirements(self):
        # 例如需要 OpenCV
        self.requires("opencv/4.5.5")
    def build(self):
        cmake = CMake(self)
        cmake.configure()
        cmake.build()
    def package(self):
        cmake = CMake(self)
        cmake.install()
    def package_info(self):
        self.cpp_info.libs = ["image_processing"]

🚀 使用方式

  1. 打包函式庫
    bash
    conan create . --version=1.0.0 --name=image_processing
    
  2. 在 CLI 專案引用
    • conanfile.txtconanfile.py 加入:
      Code
      [requires]
      image_processing/1.0.0
      
    • 然後:
      bash
      conan install . --output-folder=build --build=missing
      cmake -B build -S .
      cmake --build build
      

🎯 成果

  • 每個函式庫模組都能被打包成 Conan 套件。
  • CLI 專案只需 conan install 就能像 Python pip install 一樣引入。
  • 多專案共享同一套函式庫,避免重複編譯。

Also See

13
1:23 AM - December 07, 2025
1:23 AM - December 07, 2025
1:23 AM - December 07, 2025
1:23 AM - December 07, 2025
1:23 AM - December 07, 2025
1:23 AM - December 07, 2025
1:23 AM - December 07, 2025
1:22 AM - December 07, 2025
1:22 AM - December 07, 2025
1:22 AM - December 07, 2025
1:22 AM - December 07, 2025
1:22 AM - December 07, 2025
8:20 PM - December 06, 2025