一、在Qt工程中
一般会在类似于public_debug.h这样的头文件中定义打印调试语句,这里使用宏函数实现。
//public_debug.h
#ifndef _PUBLIC_DEBUG_H_
#define _PUBLIC_DEBUG_H_
#include <QDebug>
#define log_msg(fmt, arg...) \
do{ \
qDebug("%s,%s():%d," fmt "", __FILE__, __FUNCTION__, __LINE__, ##arg); \
}while(0)
#endif
注意:C++11要求,当字符串跟变量连接的时候,必须在format前后增加一个空格才行
二、在C语言工程中
我们也可以把程序的打印信息打印在文件中,这样方便查看打印的日志信息。
//public_debug.h
#ifndef _PUBLIC_DEBUG_H_
#define _PUBLIC_DEBUG_H_
#include <stdio.h>
//注意tmp_s数组的大小,避免数组越界问题
#define log_msg(fmt, arg...) \
do{ \
char tmp_s[512] = {0}; \
snprintf(tmp_s, sizeof(tmp_s), "%s,%s():%d," fmt "", __FILE__, __FUNCTION__, __LINE__, ##arg); \
write_file_data("debug.txt", tmp_s, sizeof(tmp_s)); \
}while(0)
#endif
//public_debug.c
#include "public_debug.h"
#include <string.h>
#include <time.h>
int local_time(char *time_buf)
{
time_t now_time = time(NULL);
struct tm *t_tm = localtime(&now_time);
if(NULL != t_tm)
memcpy(time_buf, asctime(t_tm), 24);
return 0;
}
void write_file_data(unsigned char *pFileName, unsigned char *data, int len)
{
FILE *pFilePtr = 0;
int ilen = 0;
char buf[32] = {0};
char print_res[1024] = {0};
memset(buf, 0, sizeof(buf));
if(NULL == data)
return ;
if(0 == len)
return;
pFilePtr = fopen((const char *)pFileName, "a+");
if(NULL == pFilePtr)
return ;
local_time(buf);
sprintf(print_res, "%s %s\n", buf, data);
ilen = fwrite(print_res, 1, sizeof(print_res), pFilePtr);
fclose(pFilePtr);
}
//test.c
#include "public_debug.h"
#include <stdio.h>
int main(int argc, char *argv[])
{
int a = 10;
log_msg("a = %d", a);
log_msg("finish main()");
return 0;
}
相关代码已通过调试。