C++ Deployment & Best Practices: CMake, Docker, CI/CD, RAII & Modern Guidelines (2025)
⚡ Quick Answer: C++ Deployment & Best Practices
- Build system: CMake — cross-platform, target-based, generates Make/Ninja/VS
- Dependencies: vcpkg or Conan — version-pinned, reproducible
- Containerization: multi-stage Docker — tiny production image, no compiler overhead
- CI/CD: GitHub Actions — build, test, sanitize, deploy on every push
- Linking: static for portability, dynamic for shared libraries
- Code quality: RAII + smart pointers + const correctness + noexcept
- Production flags:
-O2 -DNDEBUG -Wall -Werror
Writing correct C++ code is only half the job. Getting it reliably to production — and keeping it maintainable as the codebase grows — requires a disciplined toolchain. This guide covers the complete modern C++ production workflow: from CMake build files through multi-stage Docker containers, GitHub Actions pipelines, and the code-level practices that separate robust production code from fragile prototypes.
Deploy Steps
Full pipeline overview
CMake
Production CMakeLists.txt
Dependencies
vcpkg & Conan
Docker
Multi-stage build
CI/CD
GitHub Actions
Code Practices
RAII, const, noexcept
20-Point Checklist
Production readiness
FAQ
Common questions
C++ Deployment Pipeline — Full Overview
Code
Write & test locally
CMake Build
cmake -S . -B build
Tests
ctest + ASan/UBSan
Docker
Multi-stage image
CI/CD
GitHub Actions
Deploy
Server / Cloud
Monitor
Logs & metrics
| Aspect | Static linking | Dynamic linking |
|---|---|---|
| Library inclusion | Embedded in binary at link time | Loaded from OS at runtime |
| Binary size | Larger | Smaller |
| Portability | Self-contained — no runtime deps | Requires correct .so/.dll version |
| Security patches | Rebuild required | Update library, no rebuild |
| Best for | Docker, embedded, CLI tools | Large apps with shared libraries |
| Flag | -static or link .a files | Default (link .so / .dll) |
CMake — Production CMakeLists.txt Explained
cmake_minimum_required(VERSION 3.20) # minimum version lock
project(MyApp
VERSION 1.2.0
LANGUAGES CXX
)
# ── C++ standard ───────────────────────────────────────────────
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON) # error if 17 not available
set(CMAKE_CXX_EXTENSIONS OFF) # no GNU extensions (-std=c++17 not -std=gnu++17)
# ── Build type defaults ─────────────────────────────────────────
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
# ── Find dependencies ───────────────────────────────────────────
find_package(Threads REQUIRED) # pthreads
# find_package(Boost 1.80 REQUIRED COMPONENTS system filesystem)
# ── Targets ─────────────────────────────────────────────────────
add_executable(MyApp
src/main.cpp
src/processor.cpp
)
# Target-based includes (PRIVATE = only MyApp, not its dependants)
target_include_directories(MyApp PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include
)
target_link_libraries(MyApp PRIVATE
Threads::Threads
)
# ── Compiler warnings (per-target, not global) ──────────────────
target_compile_options(MyApp PRIVATE
$<$<CXX_COMPILER_ID:GNU,Clang>:-Wall;-Wextra;-Wpedantic>
$<$<CONFIG:Debug>:-fsanitize=address,undefined;-g;-O0>
$<$<CONFIG:Release>:-O2;-DNDEBUG>
)
target_link_options(MyApp PRIVATE
$<$<CONFIG:Debug>:-fsanitize=address,undefined>
)
# ── Embed version at compile time ───────────────────────────────
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/include/version.h.in
${CMAKE_CURRENT_BINARY_DIR}/include/version.h
)
# ── Tests ───────────────────────────────────────────────────────
enable_testing()
add_subdirectory(tests)
# ── Install rules ───────────────────────────────────────────────
install(TARGETS MyApp DESTINATION bin)
install(DIRECTORY include/ DESTINATION include)
# Debug build (with ASan + UBSan)
cmake -S . -B build/debug -DCMAKE_BUILD_TYPE=Debug
cmake --build build/debug --parallel $(nproc)
ctest --test-dir build/debug --output-on-failure
# Release build (optimized, no sanitizers)
cmake -S . -B build/release -DCMAKE_BUILD_TYPE=Release
cmake --build build/release --parallel $(nproc)
# Install to /usr/local
sudo cmake --install build/release --prefix /usr/local
# Cross-compile for ARM (with toolchain file)
cmake -S . -B build/arm -DCMAKE_TOOLCHAIN_FILE=arm-linux.cmake
include_directories()
and add_compile_options() affect every target in the project. Prefer
target_include_directories(MyLib PRIVATE ...) — it gives you precise control
over what propagates. Use PUBLIC only when downstream targets genuinely need
the include path.
Dependency Management: vcpkg vs Conan
# 1. Install vcpkg (one-time)
git clone https://github.com/microsoft/vcpkg
./vcpkg/bootstrap-vcpkg.sh
# 2. Install packages
./vcpkg/vcpkg install boost-filesystem sqlite3 openssl nlohmann-json
# 3. Create vcpkg.json (manifest mode — version-pinned)
{
"name": "myapp",
"version": "1.0.0",
"dependencies": [
"boost-filesystem",
"sqlite3",
{ "name": "openssl", "version>=": "3.0.0" },
"nlohmann-json"
]
}
cmake -S . -B build \
-DCMAKE_TOOLCHAIN_FILE=/path/to/vcpkg/scripts/buildsystems/vcpkg.cmake
# Then in CMakeLists.txt:
# find_package(nlohmann_json REQUIRED)
# target_link_libraries(MyApp PRIVATE nlohmann_json::nlohmann_json)
# conanfile.txt
[requires]
boost/1.83.0
sqlite3/3.43.2
openssl/3.1.3
[generators]
CMakeDeps
CMakeToolchain
# Install dependencies
pip install conan
conan install . --build=missing --output-folder=build
# Build with generated toolchain
cmake -S . -B build \
-DCMAKE_TOOLCHAIN_FILE=build/conan_toolchain.cmake \
-DCMAKE_BUILD_TYPE=Release
cmake --build build
include(FetchContent)
# Google Test
FetchContent_Declare(googletest
URL https://github.com/google/googletest/archive/v1.14.0.tar.gz
URL_HASH SHA256=8ad598c73ad796e0d8280b082cebd82a630d73e73cd3c70057938a6501bba5d7
)
FetchContent_MakeAvailable(googletest)
# nlohmann/json (header-only)
FetchContent_Declare(json
URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz
)
FetchContent_MakeAvailable(json)
# Use in targets
target_link_libraries(MyApp PRIVATE nlohmann_json::nlohmann_json)
target_link_libraries(tests PRIVATE GTest::gtest_main)
URL_HASH to verify integrity. For large projects with many dependencies, prefer vcpkg or Conan — they cache compiled packages across builds.
Docker — Multi-Stage Production Build
# ── Stage 1: Build ──────────────────────────────────────────────
FROM gcc:13 AS builder
WORKDIR /src
# Install CMake
RUN apt-get update && apt-get install -y cmake && rm -rf /var/lib/apt/lists/*
# Copy source (layers cached separately — CMakeLists.txt first)
COPY CMakeLists.txt .
COPY src/ src/
COPY include/ include/
# Configure and build release
RUN cmake -S . -B build -DCMAKE_BUILD_TYPE=Release && \
cmake --build build --parallel $(nproc)
# ── Stage 2: Runtime ────────────────────────────────────────────
FROM ubuntu:22.04
# Only install runtime deps (not the compiler!)
RUN apt-get update && \
apt-get install -y libstdc++6 ca-certificates && \
rm -rf /var/lib/apt/lists/*
# Copy ONLY the compiled binary from the builder stage
COPY --from=builder /src/build/MyApp /usr/local/bin/MyApp
# Non-root user for security
RUN useradd --system --no-create-home appuser
USER appuser
ENTRYPOINT ["/usr/local/bin/MyApp"]
# Build the image
docker build -t myapp:1.2.0 -t myapp:latest .
# Check final image size
docker images myapp
# builder stage: ~1.8 GB | runtime stage: ~180 MB
# Run locally
docker run --rm myapp:1.2.0
# Run with environment variables and port mapping
docker run -d \
--name myapp-prod \
-e APP_PORT=8080 \
-p 8080:8080 \
myapp:1.2.0
# Push to registry (Docker Hub or ghcr.io)
docker push myapp:1.2.0
docker push myapp:latest
GitHub Actions CI/CD Pipeline
name: C++ CI/CD
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
build-and-test:
strategy:
matrix:
os: [ubuntu-22.04, macos-14, windows-2022]
build_type: [Debug, Release]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install CMake
uses: lukka/get-cmake@latest
- name: Configure
run: |
cmake -S . -B build \
-DCMAKE_BUILD_TYPE=${{ matrix.build_type }}
- name: Build
run: cmake --build build --parallel 4
- name: Run Tests (with sanitizers in Debug)
run: ctest --test-dir build --output-on-failure
- name: Upload binary artifact
if: matrix.build_type == 'Release' && matrix.os == 'ubuntu-22.04'
uses: actions/upload-artifact@v4
with:
name: MyApp-linux
path: build/MyApp
docker-build:
needs: build-and-test
runs-on: ubuntu-22.04
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
push: true
tags: ghcr.io/${{ github.repository }}:latest
Code Best Practices: RAII, const, noexcept & Error Handling
#include <iostream>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
using namespace std;
namespace MyApp {
// RAII wrapper — resource tied to object lifetime
class DataProcessor {
unique_ptr<int[]> buffer; // RAII: freed in destructor automatically
int size;
public:
// Validate in constructor — throw on invalid state
explicit DataProcessor(int n)
: size(n), buffer(make_unique<int[]>(n))
{
if (n <= 0)
throw invalid_argument("Size must be positive");
}
// const + noexcept: read-only, optimizer-friendly
int getSize() const noexcept { return size; }
// string_view: zero-copy, no allocation
void process(string_view name) const {
cout << "Processing " << name << ": size=" << size << "\n";
}
// std::optional — no null pointers, no sentinel values
optional<int> findFirst(int target) const noexcept {
for (int i = 0; i < size; i++)
if (buffer[i] == target) return i;
return nullopt;
}
};
// Guard clause pattern — flat, readable
void run(string_view input) {
if (input.empty()) { cerr << "Error: empty input\n"; return; }
if (input.size() > 100) { cerr << "Error: input too long\n"; return; }
try {
DataProcessor p(42); // RAII: auto-cleanup
p.process(input);
auto idx = p.findFirst(7);
if (idx)
cout << "Found at index: " << *idx << "\n";
else
cout << "Not found\n";
}
catch (const exception& e) {
cerr << "Exception: " << e.what() << "\n";
}
}
} // namespace MyApp
int main(int argc, char* argv[]) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <name>\n";
return 1;
}
MyApp::run(argv[1]);
return 0;
}
Processing MyProject: size=42
Not found20-Point Production Readiness Checklist
CMake with target_* commands
No global include_directories or add_compile_options.
C++ standard pinned
CMAKE_CXX_STANDARD_REQUIRED ON, EXTENSIONS OFF.
-Wall -Wextra -Werror in CI
All warnings are errors in CI — no silent issues.
Debug builds with -fsanitize=address,undefined
Catches memory errors and UB before release.
Release builds with -O2 -DNDEBUG
Production binaries are optimized, asserts disabled.
No raw new/delete
Use unique_ptr, shared_ptr, vector, string.
RAII for all resources
Files, sockets, mutexes — all wrapped in RAII types.
const everywhere it can be
Variables, parameters, member functions.
noexcept on move ops and destructors
Enables vector move optimization and correct semantics.
Dependencies version-pinned
vcpkg.json or conanfile.txt with exact versions.
Multi-stage Docker build
Runtime image contains only binary, no compiler.
Non-root Docker user
useradd + USER appuser — principle of least privilege.
CI matrix: Linux + Windows + macOS
Catches platform-specific issues before merge.
Tests with Google Test / Catch2
ctest integrated; tests run in CI on every push.
Git version tags embedded in binary
./app --version prints commit or tag.
Debug symbols separated
strip + objcopy for smaller production binary.
Error handling at boundaries
Exceptions or optional — never silent failure.
Input validation
Validate at system boundaries; reject invalid data early.
Logging to stderr / log file
std::clog or a logging library — no silent crashes.
README with build & deploy instructions
Any new developer can build in <5 minutes from README.
FAQ / Interview Questions
std::vector<int> data; gets a correct deep-copy constructor, correct copy assignment, correct move constructor, correct move assignment, and correct destructor — all for free. Compare this to managing int* data; which requires manually defining all five correctly. Prefer the Rule of Zero..github/workflows/build.yml. Key steps: (1) actions/checkout@v4 to get the code. (2) Install CMake with lukka/get-cmake@latest. (3) Configure: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release. (4) Build: cmake --build build --parallel 4. (5) Test: ctest --test-dir build. Use a matrix to test on ubuntu-22.04, macos-14, and windows-2022 simultaneously. Run Debug builds with sanitizers and Release builds for artifacts. Gate Docker publish behind github.ref == 'refs/heads/main'.std::optional<T> when: the absence of a value is a normal, expected outcome (searching for an element that might not exist, optional configuration settings). Use exceptions when: a failure is unexpected and represents an error the caller should handle at a higher level (file not found, invalid argument, network failure). Rules: never use exceptions for normal control flow (e.g., "item not found" is not exceptional). Never silently swallow exceptions — always catch and log or re-throw. Use noexcept on functions that genuinely cannot throw.Ship production-ready C++ — from code to deployment
Structured lessons, 200+ exercises, completion certificate. Join 50,000+ students.
Related C++ Topics on CoodeVerse
Frequently asked questions
What is deployment in C++?
Deployment in C++ is the process of compiling, packaging, and distributing a C++ program to a production environment so it runs reliably. It includes: (1) compiling with optimization flags (-O2, -O3), (2) linking dependencies (static or dynamic), (3) packaging the binary and required files, (4) transferring to the target system (server, container, embedded device), (5) configuring environment variables and permissions, and (6) monitoring. Key difference from languages like Python or Java: C++ compiles to native machine code, so deployment requires platform-specific binaries — a Linux x86-64 build won't run on ARM or Windows without recompilation.
How do you use CMake for C++ deployment?
CMake is the de-facto standard C++ build system. Workflow: (1) Write a CMakeLists.txt file specifying the project name, C++ standard, source files, and dependencies. (2) Create a build directory: mkdir build && cd build. (3) Configure: cmake .. (or cmake -DCMAKE_BUILD_TYPE=Release ..). (4) Build: cmake --build . --config Release. (5) Install: cmake --install . --prefix /usr/local. Key CMake commands: add_executable(MyApp main.cpp) creates the binary target; target_link_libraries(MyApp PRIVATE some lib) links a library; install(TARGETS MyApp DESTINATION bin) adds install rules. CMake generates make files on Linux, Ninja files for speed, or Visual Studio projects on Windows — the same CMakeLists.txt works on all platforms.
How do you deploy a C++ program with Docker?
Use a multi-stage docker file to keep the production image small: Stage 1 (builder) — FROM gcc:13 AS builder; COPY . .; RUN g++ -O2 -std=c++17 main.cpp -o app. Stage 2 (runner) — FROM ubuntu:22.04; COPY --from=builder /app/app /usr/local/bin/app; CMD ['app']. This results in a tiny production image (no GCC, no sources) that contains only the binary. Build: docker build -t myapp .; Run: docker run --rm myapp. Benefits: identical environment on every machine, easy rollback (version tags), horizontal scaling via docker run or Kubernetes.
What is a CI/CD pipeline for C++ and how do I set one up?
A CI/CD (Continuous Integration/Continuous Deployment) pipeline automatically builds, tests, and deploys your C++ code on every push. GitHub Actions example: create .github/workflows/build.yml with: (1) Trigger on push/PR. (2) check out code. (3) Install GCC and CMake. (4) Configure: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release. (5) Build: cmake --build build. (6) Run tests: ctest --test-dir build. (7) Optionally deploy the binary (to a server, S3, package registry). Key benefit: catches breaking changes immediately, prevents broken code from reaching production.
What is the difference between static and dynamic linking in C++?
Static linking includes all library code in the executable at compile time: g++ main.cpp -o app /usr/lib/libfoo.a — the binary is self-contained, no runtime dependencies. Dynamic linking links at runtime against shared libraries (.so on Linux, .dll on Windows): g++ main.cpp -o app -lfoo — smaller binary, but requires the correct library version on the target system. When to use static: embedding on systems where you can't control installed libraries (Docker scratch containers, bare-metal devices). When to use dynamic: multiple programs sharing one library version, easier patching of security vulnerabilities in the library.
How do you manage C++ dependencies with vcpkg or Conan?
vcpkg (Microsoft): install vcpkg, then vcpkg install boost sqlite3 openssl. Integrate with CMake: cmake -DCMAKE_TOOLCHAIN_FILE=/path/to/vcpkg/scripts/build systems/vcpkg.cmake. vcpkg handles compilation and linking automatically. Conan: create a conan file.txt listing [requires] like boost/1.82.0, run conan install . --build=missing, then include the generated toolchain in cmake. Both tools: pin dependency versions for reproducible builds, cache compiled packages, support hundreds of libraries. vcpkg is simpler for Windows/MSVC; Conan is more flexible for cross-compilation and multi-configuration setups.
What is RAII in C++ and why is it a best practice?
RAII (Resource Acquisition Is Initialization) is the C++ pattern where a resource (heap memory, file handle, mutex, socket) is acquired in a constructor and released in the corresponding destructor. Since C++ guarantees destructors run when objects leave scope — even when exceptions are thrown — RAII guarantees resources are always cleaned up with no manual cleanup code. Examples: std::unique_ptr acquires ownership in the constructor, calls delete in the destructor; std::ifstream opens a file in the constructor, closes it in the destructor; std::lock_guard locks a mutex in the constructor, unlocks in the destructor. RAII is the foundation of leak-free, exception-safe C++.
What are the most important C++ best practices in 2025?
Top 10 C++ best practices for 2025: (1) Use smart pointers (unique_ptr, shared_ptr) — eliminate manual delete. (2) Apply RAII for all resources. (3) Compile with -Wall -Wextra -Werror in CI. (4) Use -fsanitize=address,undefined in debug builds. (5) Prefer std::string/std::string_view over C strings. (6) Mark functions const and noexcept where correct. (7) Use std::optional, std::variant, std::expected for safer APIs. (8) Follow the Rule of Five or use Rule of Zero (let compiler generate all). (9) Use CMake for all builds. (10) Write tests with Google Test or Catch2 and run them in CI.
What is the Rule of Zero in modern C++?
The Rule of Zero states: if you can design your class so that it manages no raw resources directly, you need not define any of the five special functions (destructor, copy constructor, copy assignment, move constructor, move assignment) — let the compiler generate correct ones automatically. Achieve this by using RAII member types: std::vector<T> instead of T*, std::unique_ptr instead of raw new, std::string instead of char*. When all members follow RAII, the compiler-generated copy/move/destructor do the right thing automatically. Prefer the Rule of Zero over the Rule of Three/Five — less code, fewer bugs.
How do you handle errors in C++ production code?
Three approaches: (1) Exceptions (std::exception, custom exception types): throw on failure, catch at the boundary. Best for: unexpected errors, constructors (which have no return type). (2) Return codes / std::optional<T>: return nullopt or std::unexpected on failure. Best for: performance-critical code, C-style APIs. (3) std::expected<T, E> (C++23): type-safe return-or-error without exceptions. Best for: functional-style error propagation. Guidelines: never silently swallow exceptions (catch and re-throw or log). Never use exceptions for normal control flow. Always validate inputs at system boundaries. Use noexcept on functions that genuinely cannot throw — enables compiler optimizations.
What should a production C++ CMakeLists.txt include?
A production CMakeLists.txt should include: cmake_minimum_required(VERSION 3.20) — minimum version lock. project(MyApp VERSION 1.0.0 LANGUAGES CXX) — project info. set(CMAKE_CXX_STANDARD 17) + set(CMAKE_CXX_STANDARD_REQUIRED ON) — enforce standard. Separate debug/release flags with target_compile_options. find_package for dependencies. add_executable or add_library for targets. target_link_libraries with PRIVATE/PUBLIC/INTERFACE keywords. enable_testing() + add_test() for CTest. install(TARGETS ...) for packaging. CPack for creating distributable packages. Use target_* commands (target_include_directories, target_compile_definitions) over global commands (include_directories).
What is noexcept in C++ and when should I use it?
noexcept is a specifier that promises a function will not throw exceptions. When violated (an exception escapes a noexcept function), std::terminate() is called immediately. Use noexcept on: (1) Move constructors and move assignment operators — std::vector uses move during reallocation only when noexcept. (2) Destructors — throwing in a destructor is almost always a bug. (3) Simple getters and trivial operations. (4) Any function that logically cannot fail. noexcept enables compiler optimizations: the compiler can eliminate exception-handling code on the call stack. Use noexcept(noexcept(expression)) for conditional noexcept based on member types.
How do I strip debug symbols for a smaller C++ production binary?
Three approaches: (1) Strip at compile time: use -O2 -DNDEBUG without -g (no debug symbols). (2) Separate debug info: compile with -O2 -g, then run obj copy --only-keep-debug app app.debug and strip --strip-debug app — keep the .debug file for crash symbol lookup. (3) CMake: set CMAKE_BUILD_TYPE=Release — automatically applies -O2 -DNDEBUG, no debug symbols. Use obj dump -h app to verify no .debug_info section. Stripped binaries are typically 30-80% smaller than debug builds. For production crashes, use addr2line with the pre served .debug file to resolve addresses to source lines.
What is const correctness in C++ and why does it matter?
Const correctness means consistently marking variables, function parameters, and member functions const when they do not modify state. Benefits: (1) Documents intent — callers know a function won't modify their data. (2) Enables compiler optimizations — const values can be cached in registers. (3) Allows passing to const reference parameters without copies. (4) Prevents accidental modification bugs. Apply: const int x = 5 for immutable variables; void f(const string& s) for read-only parameters; int size() const for methods that don't modify the object; const string& get name() const for getters. Start with const everywhere and remove only when modification is required.
What are the most common C++ deployment mistakes?
Top 7 deployment mistakes: (1) Not testing on the target platform — a Linux build fails on Windows, or an x86-64 build fails on ARM. (2) Dynamic dependency mismatch — library .so version on the target differs from the build machine. Fix: static link or use Docker. (3) No optimization flags — shipping a -O0 binary is 5-10x slower than -O2. (4) Debug symbols in production — includes source paths, function names; security risk and larger binary. (5) No CI/CD — manual deployment leads to 'it works on my machine' failures. (6) Missing error handling — program crashes silently in production instead of logging. (7) No version tagging — can't roll back a broken release.
What is CMake target-based approach and why is it preferred?
CMake's modern target-based approach uses target_* commands instead of global commands. Instead of: include_directories(/path/to/include) — which affects ALL targets — use: target_include_directories(MyLib PUBLIC /path/to/include). The PUBLIC/PRIVATE/INTERFACE keywords propagate properties: PRIVATE: only the target itself. PUBLIC: the target AND anything that links to it. INTERFACE: only things that link to it (for header-only libraries). This gives precise control over what propagates and prevents sub tle bugs from unexpected global state. The same applies to: target_link_libraries, target_compile_options, target_compile_definitions.
How do you write a multi-stage Dockerfile for C++?
Multi-stage builds separate the build environment from the runtime environment: Stage 1 (builder): FROM gcc:13 AS builder; work dir /src; COPY CMakeLists.txt .; COPY src/ src/; RUN cmake -S . -B build -DCMAKE_BUILD_TYPE=Release && cmake --build build. Stage 2 (runner): FROM ubuntu:22.04; RUN apt-get update && apt-get install -y libstdc++6 && rm -rf /var/lib/apt/lists/*; COPY --from=builder /src/build/myapp /usr/local/bin/myapp; entry point ['myapp']. Result: the production image contains only the binary and runtime dependencies — no GCC, no source code, no build tools. Production image is typically 50-200MB instead of 1-2GB for the full compiler image.
What is std::optional and when should I use it in C++?
std::optional<T> (C++17) represents a value that may or may not be present, without using null pointers. Use it for: function return values that may fail without throwing: std::optional<User> find user(int id) — returns nullopt if not found. Optional constructor parameters: struct Config { std::optional<int> timeout; }. Instead of sentinel values like -1 or nullptr. Access: if (auto u = find user(id)) { use(*u); } or value_or(default). Never dereference without checking: *opt when opt is empty is undefined behavior. Prefer optional over raw pointers for optional values — it's self-documenting and eliminates null dereference risk.
What is Google Test and how do I add unit tests to a C++ project?
Google Test (GTest) is the most widely used C++ unit testing framework. To add it via CMake: include(FetchContent); FetchContent_Declare(google test URL ...); FetchContent_make available(google test). Create a test file: #include <gtest/gtest.h>; TEST(math test, Addition) { EXPECT_EQ(add(2,3), 5); EXPECT_NE(add(2,3), 6); }; int main(int argc, char** argv) { testing::init googletest(&argc, argv); return RUN_ALL_TESTS(); }. Add to CMake: add_executable(tests test_main.cpp); target_link_libraries(tests GTest::gtest_main); enable_testing(); add_test(NAME MyTests COMMAND tests). Run: cmake --build build && ctest --test-dir build. Integrate into GitHub Actions CI.
How do you version a C++ binary for deployment?
Three versioning approaches: (1) CMake project version: project(MyApp VERSION 2.1.0) — then use configure_file to embed version in a header: #define APP_VERSION "${PROJECT_VERSION}". (2) Git-based version: execute git describe --tags --always at cmake configure time to embed the commit tag. (3) Build-time macro: g++ -DVERSION='"2.1.0"' main.cpp. Expose version via CLI: --version flag or a REST end point for services. Tag Docker images: docker build -t myapp:2.1.0 -t myapp:latest. Always tag releases in Git: git tag v2.1.0 && git push --tags. Semantic versioning (MAJOR.MINOR.PATCH) communicates breaking changes, new features, and bug fixes.