多等级debug输出的简单例子(c编译器: gcc(支持C99标准))

  利用C99标准支持的__VA_ARGS__宏 (C99 宏支持取参数 #define Macro(...) __VA_ARGS__   使用宏的时候,参数如果不写,宏里用 #,## 这样的东西会扩展成空串。(以前会出错的)),做的带多等级debug输出的简单例子,便于程序开发!

#include <stdio.h>
#include <stdarg.h>
#define BUFFER_SIZE 1024

#define DEBUG_LEVEL      4

typedef enum{
    DEBUG_LEVEL_ERROR=0,
    DEBUG_LEVEL_WARNING,
    DEBUG_LEVEL_NOTICE,
    DEBUG_LEVEL_INFO,
    DEBUG_LEVEL_DEBUG
}ErrorLevel;

#define transDebug(level)                       \
do{                                             \
    switch(level)                               \
    {                                           \
        case 0:                                 \
                printf("Error: ");              \
                break;                          \
        case 1:                                 \
                printf("Warning: ");            \
                break;                          \
        case 2:                                 \
                printf("Notice: ");             \
                break;                          \
        case 3:                                 \
                printf("Information: ");        \
                break;                          \
        case 4:                                 \
                printf("Debug: ");              \
                break;                          \
        default:                                \
                printf("Unknown Level: ");      \
    }                                           \
  }while(0)
#define debugPrint(debugLevel,format,...)                       \
do                                                              \
{                                                               \
    if(debugLevel<DEBUG_LEVEL)                                  \
    {                                                           \
        printf("%s(line:%d): ",__FILE__,__LINE__,debugLevel);   \
        transDebug(debugLevel);                                 \
        printf(format,##__VA_ARGS__);                             \
    }                                                           \
}while(0)


int main(int argc,char **argv)
{
    int string[3];
    const char *hello="hello the world";
    int num=5+3;
    debugPrint(5,"hello the world\n");
    //debugPrint(2); error
    debugPrint(1,"hello:%s\n",hello);
    debugPrint(3,"%s--->%d\n",hello,sizeof(string)/sizeof(int));
    return 0;
}


 

 

结果:

  lin@lin-host:~$ gcc test.c
  lin@lin-host:~$ ./a.out
      test.c(line:57): Warning: hello:hello the world
      test.c(line:58): Information: hello the world--->3

posted on 2012-07-20 16:58  lin_victor  阅读(577)  评论(1编辑  收藏  举报

导航