×
嵌入式 > 技术百科 > 详情

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

发布时间:2024-05-18 发布时间:
|

在使用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 %drn", 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()函数中,输出一些提示性的信息,来方便自己调试。


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


『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
实时控制.安全.如何加速实现未来工厂落地?