← 返回课程: Modern C++ from scratch

CMake and project best practices

视频即将上线

Compiling by hand with g++ is fine for two files, but it becomes painful with twenty: you must list every .cpp, repeat the flags and remember what changed. Besides, each operating system and compiler has its own way of building. CMake is the de facto standard tool to describe a C++ project once and generate the right build files for each platform (Makefiles, Ninja, Visual Studio projects). You write a text file called CMakeLists.txt and CMake does the rest. Today you will learn the minimum to organize a project professionally.

A minimal CMakeLists.txt

The recommended structure separates folders: include/ for public headers, src/ for the .cpp files and tests/ for tests. In CMakeLists.txt you declare the minimum version, the project name, the C++ standard and an executable (target) with its sources. The modern idea is to configure each target with its own options (target_include_directories, target_compile_options) instead of global variables. Set the standard with CMAKE_CXX_STANDARD and CMAKE_CXX_STANDARD_REQUIRED ON so it fails if the compiler does not support it, and disable compiler-specific extensions for portable code.

cmake
cmake_minimum_required(VERSION 3.16)
project(Inventory VERSION 1.0 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# the program: one executable target
add_executable(inventory
    src/main.cpp
    src/product.cpp
    src/store.cpp
)
target_include_directories(inventory PRIVATE include)

# warnings differ between compilers
if(MSVC)
    target_compile_options(inventory PRIVATE /W4)
else()
    target_compile_options(inventory PRIVATE -Wall -Wextra -Wpedantic)
endif()

# optional tests run with: ctest --test-dir build
enable_testing()
add_executable(store_tests tests/store_tests.cpp src/product.cpp src/store.cpp)
target_include_directories(store_tests PRIVATE include)
add_test(NAME store_tests COMMAND store_tests)

To build, use a separate directory so as not to mix generated files with your code: cmake -S . -B build configures the project, cmake --build build compiles, and the executable ends up inside build (with Visual Studio, in a Debug or Release subfolder). To optimize add -DCMAKE_BUILD_TYPE=Release to the first command. If you delete the build folder you lose everything except your code, which is why build/ is not committed to version control: add it to .gitignore. When you add a new .cpp, remember to list it in add_executable and run cmake again.

Best practices that make the difference

  • Enable warnings (-Wall -Wextra) and treat them as your own errors: a warning ignored today is a bug tomorrow.
  • Use RAII and smart pointers; avoid new and delete in application code.
  • Pass large objects by const reference and mark const everything that does not change.
  • Prefer the standard library (vector, string, algorithms) over hand-written code.
  • Use clear names and a consistent style; a formatter like clang-format avoids arguments.
  • Sometimes compile with -fsanitize=address,undefined to detect out-of-range accesses and undefined behavior.
  • Write small tests for the important rules and run them with every change.

You do not need a testing library to start: assert from <cassert> checks a condition and aborts the program with a message if it is false. It is enough for a study project. Keep in mind that assert is disabled if you compile with -DNDEBUG, which is what Release mode does; so use it for tests, not to validate user input.

cpp
// ---- tests/store_tests.cpp ----
#undef NDEBUG   // keep assert active even in Release builds
#include <cassert>
#include <iostream>
#include <stdexcept>

#include "store.h"

int main() {
    Store store;
    store.add(Product{"pen", 1.5, 10});

    assert(store.size() == 1);
    assert(store.find("pen") != nullptr);
    assert(store.find("ghost") == nullptr);

    bool thrown = false;
    try {
        store.remove("ghost");
    } catch (const std::out_of_range&) {
        thrown = true;
    }
    assert(thrown);

    std::cout << "all tests passed\n";
    return 0;
}

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →