代码解析:
// 在 hello.h 文件中代码如下
#ifndef hello_h // 如果hello_h宏没有被定义
#define hello_h // 定义hello_h宏
// c code
#endif // 结束条件编译
作用:
- 防止重复包含:当同一个头文件被多次
#include时,避免编译错误 - 避免重复定义:防止类、函数、变量等被重复定义
实际使用示例:
// hello.h
#ifndef hello_h
#define hello_h
// 头文件的实际内容
void sayHello();
int add(int a, int b);
#endif
工作流程:
第一次包含hello.h → hello_h未定义 → 执行#ifndef到#endif之间的内容
第二次包含hello.h → hello_h已定义 → 跳过整个内容
现代替代方案:
C++11引入了#pragma once,作用相同但更简洁:
#pragma once
void sayHello();
int add(int a, int b);
浙公网安备 33010602011771号