Chinaunix首页 | 论坛 | 博客
  • 博客访问: 19300
  • 博文数量: 5
  • 博客积分: 60
  • 博客等级: 民兵
  • 技术积分: 25
  • 用 户 组: 普通用户
  • 注册时间: 2007-04-02 18:42
文章分类

全部博文(5)

文章存档

2013年(5)

我的朋友

分类: C/C++

2013-07-11 00:06:26

为了方便调试C程序,写了个打印信息的宏,能够打印错误信息,以及错误发生的文件名、行号。

  1. #ifndef _DEBUG_H_
  2. #define _DEBUG_H_

  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <malloc.h>

  6. #define ERRBUFLEN 1024

  7. #ifdef DEBUG_ON
  8. #define ERR_PRINT(str) \
  9.     do \
  10.     { \
  11.         char errbuf[ERRBUFLEN] = {'\0'}; \
  12.         snprintf(errbuf, ERRBUFLEN, "[file: %s line: %d] %s", \
  13.                                     __FILE__, __LINE__, str); \
  14.         fprintf(stderr, "\033[31m"); \
  15.         perror(errbuf); \
  16.         fprintf(stderr, "\033[0m"); \
  17.     } while (0)
  18. #define INFO_PRINT(str) \
  19.     do \
  20.     { \
  21.         printf("\033[31m"); \
  22.         printf("[file: %s line: %d] %s\n", __FILE__, __LINE__, str); \
  23.         printf("\033[0m"); \
  24.     } while(0)
  25. #else
  26. #define ERR_PRINT(str)
  27. #define INFO_PRINT(str)
  28. #endif

  29. #endif
测试程序:

  1. #include "debug.h"

  2. int
  3. main()
  4. {
  5.         printf("test\n");

  6.         FILE *fp = NULL;

  7.         fp = fopen("./none.txt", "r");
  8.         if (fp == NULL)
  9.         {
  10.                 ERR_PRINT("fopen error");
  11.         }

  12.         int i = 1;

  13.         if (i < 2)
  14.         {
  15.                 INFO_PRINT("i < 2");
  16.         }

  17.         return 0;
  18. }

  1. [winway@s211 err_print]$ gcc test.c
  2. [winway@s211 err_print]$ ./a.out
  3. test
  4. [winway@s211 err_print]$ gcc test.c -DDEBUG_ON
  5. [winway@s211 err_print]$ ./a.out
  6. test
  7. [file: test.c line: 13] fopen error: No such file or directory
  8. [file: test.c line: 20] i < 2
欢迎使用。
阅读(1663) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~