- 话不多说, 下面通过简单的说明几个例子说明这几个的用法
定义与取消定义
-
定义
AAA
为111
#define AAA 111
-
定义
AAA
, 但没定义AAA
的值
#define AAA
-
取消定义
AAA
, 之前定义的AAA
无效
#undef AAA
选择性定义
- 如果定义了
AAA
, 那么就定义ZZZ
为222
#ifdef AAA
#define ZZZ 222
#endif
- 如果没有定义
AAA
, 那么就定义ZZZ
为222
#ifndef AAA
#define ZZZ 222
#endif
- 如果定义了
AAA
并且定义了BBB
, 那么就定义ZZZ
为222
#if defined(AAA) && defined(BBB)
#define ZZZ 222
#endif
- 如果定义了
AAA
或者定义了BBB
, 那么就定义ZZZ为222
#if defined(AAA) || defined(BBB)
#define ZZZ 222
#endif
- 如果定义了
AAA
并且没有定义了BBB
, 那么就定义ZZZ为222
#if defined(AAA) && (!defined(BBB))
#define ZZZ 222
#endif
||
和&&
也可以混合使用, 为了避免逻辑混乱, 最好加上必要的括号- 也可以结合
#elif
,#else
一起使用, 相当于if - else if - else
结构中的else if
,else
#if (defined(AAA) && defined(BBB)) || defined(CCC)
#define ZZZ 222
#elif (defined(AAA) && defined(BBB)) || (!defined(CCC))
#define ZZZ 333
#else
#define ZZZ 444
#endif
典型用法
- 在
xxx.h
文件中, 通常会使用以下方式避免头文件的重复包含
// xxx.h
#ifndef _XXX_H_
#define _XXX_H_
...
#endif
备注:欢迎关注个人微信公众号 IoTlittleHu , 第一时间获取最新文章。提供一个QQ交流群, 欢迎入群,共同学习!共同进步!
![](https://gitee.com/leafguo/image/raw/master/qq_group_QR_code/qq_group_QR_code.png)