The Ultimate Guide to C++ Conan | Modern C++ Package Management

The Ultimate Guide to C++ Conan | Modern C++ Package Management

이 글의 핵심

Conan 2.x workflows: recipes, profiles, lockfiles, and CMakeDeps/CMakeToolchain for reproducible C++ dependency graphs.

What is Conan? Why Do You Need It?

Problem Scenario: Dependency Hell

The Problem: You want to use Boost, fmt, spdlog, and OpenSSL in your C++ project. You have to manually download and build each library, then hardcode the header and library paths in your CMakeLists.txt. If your team members have different environments, paths may differ, causing build failures. When you update versions, you have to repeat the entire process.

The Solution: Conan is a C++ package manager, similar to Python’s pip or Node.js’s npm. By specifying dependencies in a conanfile.txt, Conan automatically downloads, builds, and generates CMake configuration files for you. Team members can simply run conan install to set up the same environment.

flowchart LR
    subgraph input["Input"]
        conanfile["conanfile.txt\nboost/1.80.0\nfmt/9.1.0"]
    end
    subgraph conan["Conan"]
        install["conan install"]
        download["Download packages"]
        build["Build (if needed)"]
        gen["Generate CMake files"]
    end
    subgraph output["Output"]
        cmake["conan_toolchain.cmake"]
        deps["CMakeDeps"]
    end
    conanfile --> install
    install --> download
    download --> build
    build --> gen
    gen --> cmake
    gen --> deps

Table of Contents

  1. Installing and Basic Usage of Conan
  2. conanfile.txt vs conanfile.py
  3. CMake Integration
  4. Profiles and Settings
  5. Common Issues and Solutions
  6. Production Patterns
  7. Complete Example: Multi-Library Project

1. Installing and Basic Usage of Conan

Installation

# Install using pip
pip install conan

# Check version
conan --version

# Conan 2.x is recommended

Basic Workflow

# 1. Create conanfile.txt
cat > conanfile.txt << 'EOFC'
[requires]
boost/1.80.0
fmt/9.1.0

[generators]
CMakeDeps
CMakeToolchain
EOFC

# 2. Install dependencies
conan install . --output-folder=build --build=missing

# 3. Build with CMake
cd build
cmake .. -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake -DCMAKE_BUILD_TYPE=Release
cmake --build .

Structure of conanfile.txt

[requires]
boost/1.80.0
fmt/9.1.0
spdlog/1.11.0

[generators]
CMakeDeps
CMakeToolchain

[options]
boost:shared=False
fmt:header_only=True

2. conanfile.txt vs conanfile.py

conanfile.txt (For Simple Projects)

[requires]
boost/1.80.0
fmt/9.1.0

[generators]
CMakeDeps
CMakeToolchain

conanfile.py (For Complex Projects)

from conan import ConanFile
from conan.tools.cmake import cmake_layout

class MyProjectConan(ConanFile):
    name = "myproject"
    version = "1.0"
    settings = "os", "compiler", "build_type", "arch"
    
    def requirements(self):
        self.requires("boost/1.80.0")
        self.requires("fmt/9.1.0")
        
        # Conditional dependencies
        if self.settings.os == "Linux":
            self.requires("openssl/3.0.0")
    
    def configure(self):
        # Set options
        self.options["boost"].shared = False
    
    def layout(self):
        cmake_layout(self)
    
    def generate(self):
        # Custom generation logic
        pass

3. CMake Integration

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)
project(MyProject)

set(CMAKE_CXX_STANDARD 20)

# Use files generated by Conan
find_package(Boost REQUIRED COMPONENTS filesystem)
find_package(fmt REQUIRED)

add_executable(myapp main.cpp)

target_link_libraries(myapp PRIVATE
    Boost::filesystem
    fmt::fmt
)

Build Script

#!/bin/bash

# Install dependencies
conan install . --output-folder=build --build=missing \
    -s build_type=Release \
    -s compiler.cppstd=20

# Build with CMake
cd build
cmake .. -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake \
         -DCMAKE_BUILD_TYPE=Release
cmake --build . -j$(nproc)

4. Profiles and Settings

Checking Profiles

# Default profile
conan profile show default

# Detect profiles
conan profile detect

Custom Profiles

# Create a profile
cat > ~/.conan2/profiles/gcc12 << 'EOFP'
[settings]
os=Linux
arch=x86_64
compiler=gcc
compiler.version=12
compiler.libcxx=libstdc++11
compiler.cppstd=20
build_type=Release
EOFP

# Use the profile
conan install . --profile=gcc12 --output-folder=build --build=missing

Installing by Build Type

# Debug
conan install . -s build_type=Debug --output-folder=build/debug --build=missing

# Release
conan install . -s build_type=Release --output-folder=build/release --build=missing

5. Common Issues and Solutions

Issue 1: Package Not Found

Symptom: ERROR: Package 'boost/1.80.0' not found in local cache.

Cause: The package is not in the local cache and cannot be found in remotes.

# Solution 1: Build locally with --build=missing
conan install . --build=missing

# Solution 2: Add a remote repository
conan remote add conancenter https://center.conan.io

# Solution 3: Search for the package
conan search boost --remote=conancenter

Issue 2: Compiler Version Mismatch

Symptom: ERROR: Missing prebuilt package for 'boost/1.80.0'.

Cause: No prebuilt package matches the compiler version in the profile.

# Solution 1: Build locally with --build=missing
conan install . --build=missing

# Solution 2: Update the profile
conan profile detect --force

# Solution 3: Specify a specific compiler version
conan install . -s compiler.version=11 --build=missing

Issue 3: CMake Integration Fails

Symptom: find_package(Boost) fails.

Cause: CMAKE_TOOLCHAIN_FILE is not specified.

# ❌ Incorrect usage
cmake ..

# ✅ Correct usage
cmake .. -DCMAKE_TOOLCHAIN_FILE=build/conan_toolchain.cmake

Issue 4: Build Type Mismatch

Symptom: Installed in Debug mode but built in Release mode, causing linker errors.

Cause: Mismatch between Conan’s build_type and CMake’s build type.

# Match the build type
conan install . -s build_type=Release --output-folder=build --build=missing
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake

6. Production Patterns

Pattern 1: Supporting Multiple Build Types

# Debug
conan install . -s build_type=Debug --output-folder=build/debug --build=missing
cmake -B build/debug -DCMAKE_BUILD_TYPE=Debug \
      -DCMAKE_TOOLCHAIN_FILE=build/debug/conan_toolchain.cmake

# Release
conan install . -s build_type=Release --output-folder=build/release --build=missing
cmake -B build/release -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_TOOLCHAIN_FILE=build/release/conan_toolchain.cmake

Pattern 2: Locking Versions with Lock Files

# Create a lock file
conan lock create conanfile.txt --lockfile-out=conan.lock

# Install using the lock file (exact versions)
conan install . --lockfile=conan.lock --output-folder=build --build=missing

Pattern 3: Private Package Server

# Add company internal Artifactory
conan remote add company https://artifactory.company.com/conan

# Authenticate
conan remote login company admin -p password

# Install
conan install . --remote=company

Pattern 4: Reproducible Builds with Docker

FROM ubuntu:22.04

RUN apt-get update && apt-get install -y python3-pip cmake g++
RUN pip3 install conan

WORKDIR /app
COPY conanfile.txt .
RUN conan install . --output-folder=build --build=missing

COPY . .
RUN cd build && cmake .. -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake && make

7. Complete Example: HTTP Server

conanfile.txt

[requires]
boost/1.80.0
fmt/9.1.0
spdlog/1.11.0
openssl/3.0.0

[generators]
CMakeDeps
CMakeToolchain

[options]
boost:shared=False
boost:without_test=True

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)
project(HttpServer VERSION 1.0.0)

set(CMAKE_CXX_STANDARD 20)

find_package(Boost REQUIRED COMPONENTS system thread)
find_package(fmt REQUIRED)
find_package(spdlog REQUIRED)
find_package(OpenSSL REQUIRED)

add_executable(http_server
    src/main.cpp
    src/server.cpp
)

target_link_libraries(http_server PRIVATE
    Boost::system
    Boost::thread
    fmt::fmt
    spdlog::spdlog
    OpenSSL::SSL
)

Build

# Install dependencies
conan install . --output-folder=build --build=missing -s build_type=Release

# Build with CMake
cd build
cmake .. -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake -DCMAKE_BUILD_TYPE=Release
cmake --build . -j$(nproc)

# Run
./http_server

Key Changes in Conan 2.x

FeatureConan 1.xConan 2.x
Profiles~/.conan/profiles~/.conan2/profiles
Commandsconan install . --install-folder=buildconan install . --output-folder=build
Generatorscmake, cmake_find_packageCMakeDeps, CMakeToolchain
RecipesConanFileConanFile (API changes)

Summary

ConceptDescription
ConanC++ package manager
conanfile.txtSimple dependency declaration
conanfile.pyFor complex build logic
conan installInstalls dependencies and generates CMake files
CMakeToolchainGenerates CMake toolchain file
CMakeDepsGenerates Config files for find_package

Conan automates dependency management for C++ projects, eliminating environment discrepancies and ensuring build reproducibility.


FAQ

Q1: Conan vs vcpkg?

A: Conan is Python-based, highly flexible, and makes it easy to set up private package servers. vcpkg is developed by Microsoft, integrates well with Windows, and is simpler to use. Choose based on your team’s environment and preferences.

Q2: conanfile.txt vs conanfile.py?

A: conanfile.txt is suitable for simple projects, while conanfile.py is used for complex projects requiring conditional dependencies or custom build logic.

Q3: What is —build=missing?

A: If prebuilt packages are unavailable, build locally. It may take longer initially, but subsequent builds will use cached packages.

Q4: Why are profiles important?

A: Profiles specify compiler, OS, architecture, build type, and more. Standardizing profiles across a team eliminates environment discrepancies.

Q5: Where is the Conan cache?

A: Packages are cached in ~/.conan2/p/. Use conan cache clean to clear it.

Q6: Where can I learn more about Conan?

A:

TL;DR: Use Conan to automate C++ dependency management. Next, check out our vcpkg guide!

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ vcpkg 완벽 가이드 | Microsoft C++ 패키지 관리자
  • C++ CMake 완벽 가이드 | 크로스 플랫폼 빌드·최신 CMake 3.28+ 기능·프리셋·모듈
  • C++ CMake find_package 완벽 가이드 | 외부 라이브러리 통합


이 글에서 다루는 키워드 (관련 검색어)

C++, conan, package, dependency, tools, build 등으로 검색하시면 이 글이 도움이 됩니다.