为什么在C++头文件中需要#ifndef和#define?
大家好!我刚开始学习C++,正在编写我的第一个由多个文件组成的程序。我有三个文件:`main.cpp`、`functions.h`和`functions.cpp`。
以下是`functions.h`的内容:
```cpp
// functions.h
void printHello();
int add(int a, int b);
```
在`functions.cpp`中,我包含了这个头文件并定义了函数:
```cpp
// functions.cpp
#include "functions.h"
#include
void printHello() {
std::cout << "Hello, world!" << std::endl;
}
int add(int a, int b) {
return a + b;
}
```
在`main.cpp`中,我也包含了`functions.h`:
```cpp
// main.cpp
#include "functions.h"
#include
int main() {
printHello();
std::cout << add(3, 4) << std::endl;
return 0;
}
```
一切都能正常工作。但我注意到,在别人的项目中,头文件的开头经常写着类似这样的内容:
```cpp
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
// ... 声明 ...
#endif
```
我试着删除了这些行