博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

#ifndef #define #endif 含义

Posted on 2025-11-11 16:40  steve.z  阅读(0)  评论(0)    收藏  举报

代码解析:

// 在 hello.h 文件中代码如下
#ifndef hello_h  // 如果hello_h宏没有被定义
#define hello_h  // 定义hello_h宏

// c code

#endif // 结束条件编译

作用:

  1. 防止重复包含:当同一个头文件被多次#include时,避免编译错误
  2. 避免重复定义:防止类、函数、变量等被重复定义

实际使用示例:

// 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);