在C++中,头文件(.h或.hpp)通常用于声明函数原型、类、结构体和常量
创建一个名为constants.h的头文件。在constants.h中定义常量:// constants.h#ifndef CONSTANTS_H#define CONSTANTS_Hconst double PI = 3.14159265358979323846;const int MAX_SIZE = 100;#endif // CONSTANTS_H这里我们使用了预处理器指令#ifndef、#define和#endif来防止头文件被多次包含。这称为“头文件保护”或“包含保护”。
// main.cpp#include<iostream>#include "constants.h"int main() { double radius = 5.0; double circumference = 2 * PI * radius; std::cout << "Circumference: "<< circumference<< std::endl; int arr[MAX_SIZE]; // ... return 0;}在这个例子中,我们首先包含了constants.h头文件,然后在main.cpp中使用了定义在其中的常量PI和MAX_SIZE。这样可以确保常量的值在整个项目中保持一致,并且如果需要更改这些值,只需在头文件中进行修改即可。


