C语言基础--条件编译

来源:互联网 发布:怎么开启mysql服务 编辑:程序博客网 时间:2024/04/30 04:32
指令  用途    #           空指令,无任何效果    #include    包含一个源代码文件    #define     定义宏    #undef      取消已定义的宏    #if         如果给定条件为真,则编译下面代码    #ifdef      如果宏已经定义,则编译下面代码    #ifndef     如果宏没有定义,则编译下面代码    #elif       如果前面的#if给定条件不为真,当前条件为真,则编译下面代码,其实就是else if的简写    #endif      结束一个#if……#else条件编译块    #error      停止编译并显示错误信息


#define     HAL_LED_EN                          TRUE         /* LED指示灯使能      */#define     HAL_LED_DEFAULT_MAX_LEDS            7            /* 定义LED灯最大数目  */#define     HAL_TURN_ON_LED1                    LED1_ON      /* 点亮 LED1         */


(1)//假如定义了某个宏#if defined HAL_TURN_ON_LED1......#endif相当于#ifdef HAL_TURN_ON_LED1......#endif实例:#define  A  100#if defined A#undef   A#define  A  200#endif假如定义了A,#undef解除A定义,并重新定义A为200;很多情况下使用#ifdef即可

(2)//假如没有定义了某个宏#if !defined HAL_TURN_ON_LED1......#endif相当于#ifndef HAL_TURN_ON_LED1......#endif


(3)什么情况下需要使用defined或!defined呢?我现在碰到的情况是这样实例:    在使能 HAL_LED_EN 之时,必须保证定义了 HAL_TURN_ON_LED1,如果没有定义的话,当预处理器预处理到#error命令时将停止编译并输出用户自定义的错误消息#if (HAL_LED_EN == TRUE) && (!defined HAL_TURN_ON_LED1)#error HAL_TURN_ON_LED1 no define!#endif当然了,上面的例子也可以写成下面这样的形式#if (HAL_LED_EN == TRUE)#ifndef HAL_TURN_ON_LED1#error HAL_TURN_ON_LED1 is no defined!#endif#endif但是如果需要判断的宏定义太多,第一种写法的优势就体现出来了#if (HAL_LED_EN == TRUE) && (!defined HAL_TURN_ON_LED1) && ((!defined HAL_TURN_ON_LED2) || (!defined HAL_TURN_ON_LED3))#error HAL_TURN_ON_LED1 no define!#endif

(4)#if HAL_LED_DEFAULT_MAX_LEDS == 7#define A 100#elif (HAL_LED_DEFAULT_MAX_LEDS == 6) || (HAL_LED_DEFAULT_MAX_LEDS == 5)#define A 200#else#define A 300#endif

0 0
原创粉丝点击