标题: 嵌入式c语言调试开关 [打印本页]

作者: 51黑黑黑    时间: 2016-2-22 23:07
标题: 嵌入式c语言调试开关
本帖最后由 51黑黑黑 于 2016-2-22 23:09 编辑

调试程序时,经常会用到assert和printf之类的函数,我最近做的这个工程里就有几百个assert,在你自认为程序已经没有bug的时候,就要除去这些调试代码,应为系统在正常运行时这些用于调试的信息是无用的,而且会占用时间和空间。怎么删除呢,俺以前都是用笨方法,一个一个注释,能用注释也是经过改进的方法,俺最早都是删掉之后出了问题再重新写的,但是这次几百个一个一个删除的话可是要了俺的小命了,一首mp3听完,还不到一百个。以前看过st的函数库,老外的代码就是规范,俺现在的代码好多都是在st和ti那里照搬的,呵呵。
下面给出最简单的一种方法:
  1. #define DEBUG
  2. #ifdef DEBUG
  3. #define PRINTF(x) printf x
  4. #else
  5. #define PRINTF(x)         ((void)0)
  6. #endif
复制代码
使用时,PRINTF(( "Hello World!\n\r" ));
注意这里是两个括号,一个会报错的
不使用时,直接将"#define DEBUG"屏蔽掉
另外一个调试时常用的方法是assert,还是在一个头文件里,这里用的是STM32函数库的例子
  1. #ifdef DEBUG 1
  2. /*******************************************************************************
  3. * Macro Name : assert_param
  4. * Description : The assert_param macro is used for function's parameters check.
  5. * It is used only if the library is compiled in DEBUG mode.
  6. * Input : - expr: If expr is false, it calls assert_failed function
  7. * which reports the name of the source file and the source
  8. * line number of the call that failed.
  9. * If expr is true, it returns no value.
  10. * Return : None
  11. *******************************************************************************/

  12. #define assert_param(expr) ((expr) ? (void)0 : assert_failed((u8 *)__FILE__, __LINE__))

  13. /* Exported functions ------------------------------------------------------- */

  14. void assert_failed(u8* file, u32 line);
  15. #else
  16. #define assert_param(expr) ((void)0)
  17. #endif/* DEBUG */

  18. //assert_failed此函数要自己定义
  19. #ifdef DEBUG
  20. /*******************************************************************************
  21. * Function Name : assert_failed
  22. * Description : Reports the name of the source file and the source line number
  23. * where the assert_param error has occurred.
  24. * Input : - file: pointer to the source file name
  25. * - line: assert_param error line source number
  26. * Output : None
  27. * Return : None
  28. *******************************************************************************/
  29. void assert_failed(u8* file, u32 line)
  30. {

  31. /* User can add his own implementation to report the file name and line number,
  32. ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  33. /* Infinite loop */
  34.     while (1){
  35.     }

  36. }
  37. #endif
复制代码







欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1