一個方便打印C程序調試信息的宏

爲了方便調試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 (< 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
歡迎使用。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章