C/C++中常用的调试语句

C/C++中常用的调试语句

一、在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;
}

相关代码已通过调试。
测试结果

  • 19
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值