测试_第20章_编译模型.cpp

← 测试总览 · 目录

编译运行:clang++ -std=c++26 -Wall -Wextra -pthread 测试_第20章_编译模型.cpp -o t && ./t(需先 cd 测试/

// 第20章测试:编译模型与链接(多文件工程演示)
// 本测试由 4 个文件组成,用命令行编译:
//   cd "C++中文教程/测试"
//   clang++ -std=c++26 -Wall -Wextra \
//     主文件_第20章.cpp 附加_第20章_math.cpp 附加_第20章_util.cpp -o t20 && ./t20
// 或直接 ./测试_第20章_编译模型.sh

#include <print>
#include <string>
#include <vector>
#include <numeric>

int failures = 0;
#define CHECK(expr)                                                         \
    do {                                                                    \
        if (!(expr)) {                                                      \
            ++failures;                                                     \
            std::println("FAIL 第{}行: {}", __LINE__, #expr);              \
        }                                                                   \
    } while (0)

// 声明其他翻译单元的函数(见附加_第20章_*.cpp)
int math_add(int a, int b);
int math_square(int x);
namespace util {
int sum_all(const std::vector<int>& v);
std::string greet(const std::string& name);
}

// C++17 inline 变量:头文件风格允许的"多份定义合并"
struct InlineDemo {
    inline static int counter = 0;
};

int main() {
    // 跨文件调用:链接器把它们拼起来了
    CHECK(math_add(3, 4) == 7);
    CHECK(math_square(7) == 49);
    CHECK(util::sum_all({1, 2, 3, 4}) == 10);
    CHECK(util::greet("小明") == "你好, 小明");

    // 本文件内部实体
    static int local_private = 42;              // 内部链接:别的 .o 看不到
    CHECK(local_private == 42);

    // 头文件守卫模式验证(编译一次成功即证明无重复定义问题)
    CHECK(InlineDemo::counter == 0);

    if (failures == 0) std::println("全部通过");
    return failures;
}