| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
8年前发布

Keil 条件编译之爬坑

条件编译是编程一个很重要的,但是每一个编译器有不同的写法.经常使用不同编译就容易混淆.所以也常常跳到坑里去.

单片机的调试由于受硬件影响,调试条件不是很好.出错就会浪费很多时间.所以对条件编译的理解到位很重要.

1 #if

1 #if expression  2 .  3 .  4 .  5 #endif

可以加上 #elif,和#else

例如下面这个例子.

这个例子是针对不同电压,对程序保护添加的定义

那么先来定义不同电压

#define V36V 36     #define V48V 48    #define V576V 576

再根据不同的电压,定义保护电压.

#if VOLTAGE ==V36V    #define LowProtect 100     #define MaxVoltage 132     #define MinVoltage 112     #define MiddleVoltage 121  #elif VOLTAGE==V48V    #define LowProtect 124     #define MaxVoltage 173    #define MinVoltage 100    #define MiddleVoltage 153  #elif VOLTAGE==V576V    #define LowProtect 147     #define MaxVoltage 173    #define MinVoltage 100    #define MiddleVoltage 153    #endif

当编译的时候只要加上一条对VOLTAGE的宏定义,

#define VOLTAGE 48 

这样在编译时,只需修改 VOLTAGE 的值即可,将它修改36 即为36V的保护电压.

2 #ifdef

#ifdef name    #endif

#ifdef 表示如果定义name 就执行编译name 里面的内容.

name 也可以被定义为宏定义.

这里要特别注意,当name被定义为宏定义时 name 的值不会起作用.

#define name 1    #ifdef name  .  .  #else  .  .  #endif

还有这种情况,如下代码

#define Name1  0  #define Name2  1  #define Name3  0
#ifdef Name1     #define LowProtect 100     #define MaxVoltage 132     #define MinVoltage 112     #define MiddleVoltage 121  #endif  #ifdef Name2    #define LowProtect 124     #define MaxVoltage 173    #define MinVoltage 100    #define MiddleVoltage 153  #endif  #ifdef Name3    #define LowProtect 147     #define MaxVoltage 173    #define MinVoltage 100    #define MiddleVoltage 153    #endif

你觉得编译器会报错吗?不报错的话,会选择编译哪一个呢?

答案是不报错,会选择Name3 进行编译.

所以最好不要写成这种形式.

还是使用#if 的形式会好很多.

我就是在这里掉进了坑里,搞了一个多小时才弄清楚原因的.

keil 又不像VS一样,选择了不同的宏定义,IDE就自动将不需编译的代码显示为灰色.

所以,掉坑了很正常.

来自: http://www.cnblogs.com/TopC/p/5112269.html

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1452233966776.html
技术