模組化開發-用 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.txtcmake
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.txtcmake
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.txtcmake
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)
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"]
conan create . --version=1.0.0 --name=image_processing
conanfile.txt 或 conanfile.py 加入:[requires]
image_processing/1.0.0
conan install . --output-folder=build --build=missing
cmake -B build -S .
cmake --build build
conan install 就能像 Python pip install 一樣引入。| 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 |