程序设计中 应用断言提高程序调试效率
使用宏定义 USE_FULL_ASSERT 来开关断言使用,在调试完成后,关闭此断言调试接口
断言失败返回接口函数
#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
程序设计中断言的使用
先定义宏,规范语句易读性。
例如: #define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x10) #define IS_NVIC_SUB_PRIORITY(PRIORITY) ((PRIORITY) < 0x10) #define IS_NVIC_OFFSET(OFFSET) ((OFFSET) < 0x0005FFFF)
使用时使用
assert_param(IS_FUNCTIONAL_STATE(NVIC_InitStruct->NVIC_IRQChannelCmd)); assert_param(IS_NVIC_PREEMPTION_PRIORITY(NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority)); assert_param(IS_NVIC_SUB_PRIORITY(NVIC_InitStruct->NVIC_IRQChannelSubPriority));
使用assert_param 跳转断言失败返回函数,并指出断言失败地方。
#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 */
版权声明:本文为xiumusheng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。