一、前言
最近写C语言代码时,感觉用printf()输出不够方便,想着能不能做到和Android的Log.d()相类似,于是乎,百度了一下,封装个自己的打印函数,仅供参考。
二、封装代码
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <time.h>
/* 宏定义方式 */
#define DEBUG 1
#define LOGD(fmt, ...) {if (DEBUG == 1 ) printf("[D][%s:%d] "fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);}
#define LOGE(fmt, ...) {if (DEBUG == 1 ) printf("[E][%s:%d] "fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);}
#define LOGI(fmt, ...) {if (DEBUG == 1 ) printf("[I][%s:%d] "fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);}
/* 打印调试信息 */
void LOGD(const char* format, ...)
{
printf("Debug => ");
va_list vp;
va_start(vp, format);
vprintf (format, vp);
va_end (vp);
printf ("\n");
}
/* 打印错误信息 */
void LOGE(const char* format, ...)
{
printf("Error => ");
va_list vp;
va_start(vp, format);
vprintf (format, vp);
va_end (vp);
printf ("\n");
}
/* 打印参数信息 */
void LOGI(const char* format, ...)
{
printf("Info => ");
va_list vp;
va_start(vp, format);
vprintf (format, vp);
va_end (vp);
printf ("\n");
}
三、调用方法
LOGD("A = %d", i);
LOGE("Error: %s", error);
LOGI("This is my print function.");