C++ Overview & Toolchain Setup

What C++ is and where backend uses it, compilation stages, GCC/Clang/MSVC toolchains, CMake basics, and your first program.

BeginnerUpdated 2026-10-3041K views

Why C++ on the Backend

C++ gives full control over memory and CPU: zero-cost abstractions, deterministic performance, no garbage-collection pauses. It backs database engines (MySQL, MongoDB), search infrastructure, trading systems, game servers and embedded gateways where latency is measured in microseconds.

  • Strengths: peak performance, mature ecosystem, ABI-compatible with C and countless libraries.
  • Cost: manual memory discipline, slower builds, a bigger maintenance surface than Go or Java.

From Source to Binary

hello.cpp
   │  预处理 (#include 展开为翻译单元)
   ▼
编译 → 汇编 (.s)
   │
   ▼
汇编 → 目标文件 (.o / .obj)
   │
   ▼
链接 (ld) → 可执行文件

关键规则:头文件放声明,源文件放定义;
#pragma once / include guard 防重复包含。
# 单文件直编
g++ -std=c++20 -O2 -Wall -Wextra hello.cpp -o hello

# 分离编译:先各自编译为 .o,再链接
g++ -std=c++20 -c a.cpp -o a.o
g++ -std=c++20 -c main.cpp -o main.o
g++ a.o main.o -o app

# 常用参数
# -O0/-O2/-O3 优化级别(线上默认 -O2)
# -g            保留调试符号(gdb/性能分析必备)
# -fsanitize=address,undefined  内存/未定义行为检查(测试用)

CMake Project Skeleton

cmake_minimum_required(VERSION 3.20)
project(shop CXX)

set(CMAKE_CXX_STANDARD 20)          # 用 C++20
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(shop
    src/main.cpp
    src/order.cpp
)

target_include_directories(shop PRIVATE src)

# 第三方库:vcpkg / conan 提供 find_package
find_package(fmt CONFIG REQUIRED)
target_link_libraries(shop PRIVATE fmt::fmt)

# 测试
enable_testing()
add_subdirectory(tests)
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j            # 编译
ctest --test-dir build            # 跑测试
# 生成器:Ninja 比 Make 更快,CI 常用
# cmake -S . -B build -G Ninja

Your First Program

#include <iostream>
#include <string>

int main(int argc, char* argv[]) {
    const std::string name = (argc > 1) ? argv[1] : "BackendWiki";
    std::cout << "Hello, " << name << "!\n";
    return 0;                     // 返回 0 表示成功
}

Friends & Partners