头文件定义
#ifndef DPRINTF_H
#define DPRINTF_H
extern const char *COLOR_ARG[];
int perr(const char *file, int line, const char *funtion, int err);
#ifdef DEBUG
#define PERR(x) perr(__FILE__, __LINE__, __FUNCTION__, (x))
#define DPRINTF(x, str,...) do{fprintf(stdout, "%s%s::%s::%d:\t"str"\033[39;49;0m\n", COLOR_ARG[(x)&7], __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__);}while(0)
#define DERROR(str, ...) do{fprintf(stderr, "\033[31;1m%s::%s::%d:\t"str"\033[39;49;0m\n", __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__);}while(0)
#else
#define PERR(x) (x)
#define DPRINTF(str,...)
#define DERROR(str, ...)
#endif
#endif
源文件定义
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
const char *COLOR_ARG[] = {
"\033[37;40m",//白色
"\033[33;40m",//黄色
"\033[35;40m",//紫色
"\033[31;40m",//红色
"\033[37;5m", //白色闪烁
"\033[33;5m", //黄色闪烁
"\033[35;5m", //紫色闪烁
"\033[31;5m", //红色闪烁
};
int perr(const char *file, int line, const char *funtion, int err)
{
char buffer[1024];
if(err)
fprintf(stderr, "\033[31;1m%s::%d::%s\t%d:\t%s\033[39;49;0m\n", file, line, funtion, err, strerror_r(errno, buffer, sizeof(buffer)));
return err;
}
适合c++11 的 DPRINTF宏:
#define DPRINTF(str, ...) do{std::string __tmp = std::string("%s::%s::%d:\t") + std::string(str) + std::string("\n"); printf(__tmp.c_str(), /*"%s::%s::%d:\t"##str##"\n", */__FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__);}while(0)