"); //-->
在单片机开发中经常需要加入printf之类的函数来输出调试信息,这些信息一般伴随着整个开发过程,但是在程序发布时候,又得将它们注释掉,非常的不方便,于是有了以下解决办法:
使用宏定义开关
#ifdef __DEBUG #define DEBUG(info) printf(info) #else #define DEBUG(info) #endif
但是这样并不能发挥出printf函数的强大功能,使用起来并不方便。
使用不定参数的宏定义
c99规范后,编译器就开始支持不定参数##__VA_ARGS__的宏定义
相关知识可参考博客http://blog.csdn.net/aobai219/archive/2010/12/22/6092292.aspx
于是我们就有了这样的一个宏定义
————————————————
#ifdef __DEBUG #define DEBUG(format, ...) printf (format, ##__VA_ARGS__) #else #define DEBUG(format, ...) #endif
嗯,现在printf的功能是有了,那干脆再输出一些相关的信息,这样一下子就可以知道代码位置,然后就变成这样了:
 #ifdef __DEBUG
     #define DEBUG(format, ...) \
          printf("FILE: "__FILE__", LINE: %d: "format"/n", __LINE__,##__VA_ARGS__)
 #else
     #define DEBUG(format, ...)
 #endif/*
 * logger.h
 *
 *  Created on: 2018年01月28日
 *      Author: dj666
 */
#ifndef APP_PUBLIC_LOGGER_H_
#define APP_PUBLIC_LOGGER_H_
#define __DEBUG    //日志模块总开关,注释掉将关闭日志输出
#ifdef __DEBUG
    #define DEBUG(format, ...) printf (format, ##__VA_ARGS__)
#else
    #define DEBUG(format, ...)
#endif
//定义日志级别
enum LOG_LEVEL {    
    LOG_LEVEL_OFF=0,
    LOG_LEVEL_FATAL,
    LOG_LEVEL_ERR,
    LOG_LEVEL_WARN,
    LOG_LEVEL_INFO,
    LOG_LEVEL_ALL,
};
#define log_fatal(level,format, ...) \
    do { \
         if(level>=LOG_LEVEL_FATAL)\
           DEBUG("\n->FATAL @ FUNC:%s FILE:%s LINE:%d \n" format "\n",\
                     __func__, __FILE__, __LINE__, ##__VA_ARGS__ );\
    } while (0)
#define log_err(level,format, ...) \
    do { \
         if(level>=LOG_LEVEL_ERR)\
           DEBUG("\n->ERR   @ FUNC:%s FILE:%s LINE:%d \n" format "\n",\
                     __func__, __FILE__, __LINE__, ##__VA_ARGS__ );\
    } while (0)
#define log_warn(level,format, ...) \
    do { \
         if(level>=LOG_LEVEL_WARN)\
           DEBUG("\n->WARN  @ FUNC:%s \n" format "\n",__func__, ##__VA_ARGS__ );\
    } while (0)
#define log_info(level,format, ...) \
    do { \
         if(level>=LOG_LEVEL_INFO)\
           DEBUG("\n->INFO  \n"format"\n",##__VA_ARGS__ );\
    } while (0)
#define log_debug(level,format, ...) \
    do { \
         if(level>=LOG_LEVEL_ALL)\
           DEBUG("\n->DEBUG \n"format"\n",##__VA_ARGS__ );\
    } while (0)
#endif /* APP_PUBLIC_LOGGER_H_ */使用也非常简单,定义一个局部的变量来保存该模块的日志输出级别,下面是使用示例:
#include"logger.h"
static enum LOG_LEVEL logger=LOG_LEVEL_WARN;//模块日志输出级别
int main(void)
{ 
    logger = LOG_LEVEL_ALL; //修改模块日志输出级别
    log_debug(logger,"this is a debug");
    log_info(logger,"this is a info");
    log_warn(logger,"%s","this is a warn");
    log_err(logger,"this is a err %d ",-1);
}c语言宏定义##__VA_ARGS__封装printf函数,单片机实现简单的分级日志模块_昵称随便取啦的博客-CSDN博客
*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。