条件编译指令 #define #undef #ifdef #ifndef #endif

  • 话不多说, 下面通过简单的说明几个例子说明这几个的用法

定义与取消定义

  • 定义AAA111
    #define AAA 111

  • 定义AAA, 但没定义AAA的值
    #define AAA

  • 取消定义AAA, 之前定义的AAA无效
    #undef AAA


选择性定义

  • 如果定义了AAA, 那么就定义ZZZ222
#ifdef AAA
    #define ZZZ 222
#endif

  • 如果没有定义AAA, 那么就定义ZZZ222
#ifndef AAA
    #define ZZZ 222
#endif

  • 如果定义了AAA并且定义了BBB, 那么就定义ZZZ222
#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交流群, 欢迎入群,共同学习!共同进步!

你可能感兴趣的:(#,C/C++,c语言,宏定义,#define,条件编译)