20140626-STM8L101F3P6编程中关于assert_param()断言的小结

在使用STM8或STM32的过程中,在官方的库文件中经常能看到assert_param()的使用,一直都是对它无视,因为它不影响使用。但作为一名合格的、严谨的工程师来讲,连assert_param()断言都没搞明白,都没弄清楚,自己感觉还是有点丢人的。

其实这个就是断言,它的主要用途是在编程的过程中为程序员提供参数检查,对于Release之后,对终端用户而言是无用的。它是在开发调试过程中,对参数错误进行提示,以便程序员提高开发效率。

首先,在STM8L101F3P6官方提供的模版库的main.c文件中我们会看到如下代码:

void main(void)
{
    /* Infinite loop */
    while (1)
    {
    }

}

#ifdef  USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *   where the assert_param error has occurred.
  * @param file: pointer to the source file name
  * @param line: assert_param error line source number
  * @retval : None
  */
void assert_failed(uint8_t* file, uint32_t line)
{
    /* User can add his own implementation to report the file name and line number,
       ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

    /* Infinite loop */
    while (1)
    {
    }
}
#endif

其含义是:如果定义了USE_FULL_ASSERT宏,则程序包含了assert_failed()这个函数的定义。

在stm8l10x_conf.h文件中,我们也会看到如下的代码:

/* Exported macro ------------------------------------------------------------*/
#ifdef  USE_FULL_ASSERT

/**
  * @brief  The assert_param macro is used for function's parameters check.
  * @param expr: If expr is false, it calls assert_failed function
  *   which reports the name of the source file and the source
  *   line number of the call that failed. 
  *   If expr is true, it returns no value.
  * @retval : None
  */
  #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
/* Exported functions ------------------------------------------------------- */
  void assert_failed(uint8_t* file, uint32_t line);
#else
  #define assert_param(expr) ((void)0)
#endif /* USE_FULL_ASSERT */

这里是assert_param()的原型。

可以看到,它是一个带参数的宏定义,参数是一个条件表达式。表达式就是你要检查的参数。

表达式为真时,其定义为(void)0。即空,什么都不做,对程序无影响。函数调用时传来的参数都是正确的,不需要进行什么操作。

表达式为假时,其定义为assert_failed((uint8_t *)__FILE__,__LINE__)),这是一个带两个参数的函数,这个函数就是在main.c中定义的。第1个参数为文件指针,指示参数错误的文件;第2个参数是参数错误的等号。

--------------------------------------------------------------------------------------------------------------------------------------

1.使用时,要定义USE_FULL_ASSERT这个这宏,在stm8l10x_conf.h文件中去定义

2.可以是assert_failed()函数中,输出一些提示性的信息,来方便自己调试。

--------------------------------------------------------------------------------------------------------------------------------------

2014.06.25

于单位

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值