摘要:函数定义类成员函数的定义变量定义程序的主要逻辑// Math_utils.h#ifndef MATH_UTILS_H // 头文件保护#define MATH_UTILS_H#include// 包含标准库头文件 // 常量定义 const double PI
在C++中,头文件和源文件是组织代码的两种不同文件,作用和编写方式不同,是组织代码的基本方式,两者共同构成了项目的模块化结构
头文件扩展名为`.h`或`.hpp`,通常包含:
函数声明(原型)类定义模板定义内联函数常量定义其它预处理指定(如`#include`、宏定义等)
头文件的主要作用是声明接口,而不是实现,这样,多个源文件可以同时包含同一个头文件来使用相同的声明
源文件扩展名为`.c`或`.cpp`,通常包含:
函数定义类成员函数的定义变量定义程序的主要逻辑// Math_utils.h#ifndef MATH_UTILS_H // 头文件保护#define MATH_UTILS_H#include// 包含标准库头文件 // 常量定义 const double PI = 3.1415926535; // 函数声明 double calculateCircleArea(double radius); double calculateDistance(double x1, double y1, double x2, double y2); // 类声明 class Calculator { private: double lastResult; public: Calculator; double add(double a, double b); double multiply(double a, double b); double getLastResult const; }; // 内联函数定义 inline double square(double x) { return x * x; } #endif // MATH_UTILS_H // math_utils.cpp#include "math_utils.h" // 包含对应的头文件#include// 函数定义 double calculateCircleArea(double radius) { return PI * radius * radius; } double calculateDistance(double x1, double y1, double x2, double y2) { return std::sqrt(square(x2 - x1) + square(y2 - y1)); } // 类成员函数定义 Calculator::Calculator : lastResult(0) {} double Calculator::add(double a, double b) { lastResult = a + b; return lastResult; } double Calculator::multiply(double a, double b) { lastResult = a * b; return lastResult; } double Calculator::getLastResult const { return lastResult; } // 头文件和源文件使用相同的基名// ✅ 推荐student.h // 类 Student 的声明student.cpp // 类 Student 的实现// ✅ 也可以明确包含类名(文件中只包含一个类时)class_student.hclass_student.cpp// ❌ 避免不一致,虽然这样也没错Student.h // 头文件大写student.cpp // 源文件小写 - 不一致!// large_module.hclass LargeModule {public:void featureA;void featureB;void featureC;};// 由于实现太大,拆分成多个源文件:// large_module_feature_a.cpp#include "large_module.h"void LargeModule::featureA { /* 实现A */ }// large_module_feature_b.cpp #include "large_module.h"void LargeModule::featureB { /* 实现B */ }// large_module_feature_c.cpp#include "large_module.h" void LargeModule::featureC { /* 实现C */ }// idatabase.h - 接口class IDatabase {public:virtual void connect = 0;virtual void query(const std::string& sql) = 0;};// mysql_database.cpp - MySQL实现#include "idatabase.h"class MySQLDatabase : public IDatabase {// MySQL特定实现};// sqlite_database.cpp - SQLite实现 #include "idatabase.h"class SQLiteDatabase : public IDatabase {// SQLite特定实现};// vector_utils.h - 主要模板templateclass VectorUtils {// 通用实现};// vector_utils_specializations.cpp - 特化实现#include "vector_utils.h"// 特定类型的特化实现templateclass VectorUtilsproject/├── calculator.h├── calculator.cpp // 直接对应├── utils.h├── utils.cpp // 直接对应└── main.cppproject/├── core/│ ├── logger.h│ ├── logger.cpp // 直接对应│ ├── config.h│ └── config.cpp // 直接对应├── network/│ ├── http_client.h│ ├── http_client.cpp // 直接对应│ ├── http_request.h│ ├── http_request.cpp // 直接对应│ ├── http_response.h│ └── http_response.cpp // 直接对应└── main.cpplarge_project/├── core/│ ├── database/│ │ ├── idatabase.h // 接口│ │ ├── mysql_database.h // 实现1头文件│ │ ├── mysql_database.cpp // 实现1源文件│ │ ├── postgresql_database.h // 实现2头文件│ │ └── postgresql_database.cpp // 实现2源文件│ └── utils/│ ├── string_utils.h│ ├── string_utils.cpp // 主要实现│ ├── string_utils_unicode.cpp // 特殊功能实现│ └── string_utils_performance.cpp // 优化实现└── main.cpp不使用头文件会产生重复定义问题// main.cpp// 假设我们直接定义所有内容:// 在多个地方都需要这个函数声明void log_message(const std::string& message); // 声明1int main {log_message("Program started");return 0;}void log_message(const std::string& message) { // 定义std::cout // ✅ 有头文件的情况:// logger.h - 声明接口#ifndef LOGGER_H#define LOGGER_H#includevoid log_message(const std::string& message); void set_log_level(int level); #endif // logger.cpp - 实现细节 #include "logger.h" #includestatic int current_log_level = 1; // 实现细节,对外隐藏 void log_message(const std::string& message) { if (current_log_level > 0) { std::cout 编译时间优化// 没有头文件的情况:// 每次修改实现,所有包含该实现的文件都要重新编译// 有头文件的情况:// 修改 logger.cpp → 只需重新编译 logger.cpp// 修改 logger.h → 需要重新编译所有包含它的文件// ❌ 没有头文件的问题:// file1.cppvoid helper_function; // 声明void function_a {helper_function;}// file2.cpp void helper_function; // 重复声明!void function_b {helper_function;}// file3.cppvoid helper_function { // 实际定义// 实现...}// ✅ 使用头文件的解决方案:// helper.hvoid helper_function;// file1.cpp#include "helper.h"void function_a {helper_function; // 统一的声明}// file2.cpp#include "helper.h" void function_b {helper_function; // 统一的声明}// helper.cpp#include "helper.h"void helper_function {// 实现...}// ❌ 没有头文件的类使用问题:// main.cppclass Student { // 必须在每个使用的地方都定义类private:std::string name;int age;public:Student(const std::string& name, int age);void display const;};// 如果多个文件需要使用Student,每个文件都要重复类定义!// ✅ 使用头文件的解决方案:// student.hclass Student {private:std::string name;int age;public:Student(const std::string& name, int age);void display const;};// main.cpp#include "student.h" // 一次定义,到处使用// teacher.cpp #include "student.h" // 同样的类定义// ✅ 小型工具、测试代码、学习示例// simple_program.cpp#include// 直接在同一个文件中定义和使用 void helper { std::cout class SimpleContainer { // 模板实现通常在头文件中 };// math_operations.h - 清晰的接口契约#ifndef MATH_OPERATIONS_H#define MATH_OPERATIONS_H// 明确的输入输出说明double calculate_circle_area(double radius);int factorial(int n);bool is_prime(int number);#endif// 使用者只需要看头文件就知道如何使用// 不需要关心复杂的实现细节// 团队开发场景:// developer_a 负责接口设计// math_api.hclass MathAPI {public:virtual double compute(const std::string& expression) = 0;};// developer_b 负责实现// math_implementation.cpp #include "math_api.h"class MathImplementation : public MathAPI {public:double compute(const std::string& expression) override {// 复杂实现...}};// developer_c 负责使用// app.cpp#include "math_api.h"// 可以基于接口开发,不依赖具体实现// 作为库开发者,你可以:// 只提供头文件和编译后的二进制文件// mylib.h - 头文件(给用户)class MyLib {public:void public_api;private:void* implementation_details; // 隐藏实现};// mylib.cpp - 源文件(不提供给用户)#include "mylib.h"void MyLib::public_api {// 专利算法,源代码保密}// 用户只需要:#include "mylib.h" // 和链接你的二进制库// 1. 重复包含保护#ifndef MY_HEADER_H // 样板代码#define MY_HEADER_H// ...#endif// 2. 编译依赖// 修改头文件 → 所有包含它的源文件重新编译// 3. 可能的循环依赖// a.h 包含 b.h, b.h 又包含 a.hC++20引入了模块(利用`export`和`import`关键字),试图解决头文件的一些问题:
// math_utils.ixx - 模块接口文件,注意后缀export module MathUtils;export double calculate_area(double radius) {return 3.14159 * radius * radius;}export class Calculator {public:double add(double a, double b) { return a + b; }};// main.cpp - 使用模块import MathUtils;int main {Calculator calc;double result = calc.add(5, 3);return 0;}详情可查看 C++中的头文件和源文件-CSDN博客
来源:有趣的科技君