【C语言】assert_param的意义与一个应用举例

(4) 2024-05-09 12:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说【C语言】assert_param的意义与一个应用举例,希望能够帮助你!!!。

用于判断一个初始化值,是否符合平台设置。举个例子,其他的类似的。

比如stm32中的时钟格式,时钟格式为12或者24,并且事先用宏定义12和24。

//头文件,默认定义宏

#define RTC_HOURFORMAT_24              0x00000000U
#define RTC_HOURFORMAT_12              0x00000040U 

//用于判断预设变量是否正确,正确返回1

#define IS_RTC_HOUR_FORMAT(FORMAT)        ((FORMAT) == RTC_HOURFORMAT_12) ||         \
                                                                                        ((FORMAT) == RTC_HOURFORMAT_24)

//实际中使用

assert_param(IS_RTC_HOUR_FORMAT(hrtc->Init.HourFormat))

#define assert_param(expr)        ((void)0U)

//如果是默认值则为1,就什么都不做。否则调用asser_failed函数

#define assert_param(expr)    (expr)?(void)0:assert_failed((uint8_t*)__FILE, __LINE__))

//assert函数是main.c里的一个自定义函数,提示example可以是用printf打印

#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

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复