C/C++打印当前函数名,代码函数,文件名及常用调式函数

#include <stdio.h>

void func()
{
 	printf("this is test\n");
	printf("%s\n",__FILE__);//当前文件名
	printf("%s\n",__func__);//当前函数名
	printf("%d\n",__LINE__);//当前代码行数
}
int main()
{	
	func();
	printf("%s\n",__FILE__);//当前文件名
	printf("%s\n",__func__);//当前函数名
	printf("%d\n",__LINE__);//当前代码行数

}
    printf("file=%s,func=%s,line=%d\n",__FILE__,__FUNCTION__,__LINE__);

    printf("%s,%d \n",__PRETTY_FUNCTION__,__LINE__);


  • 通过模仿printf函数来打印日志,或者保存到文件中
  • __VA_ARGS__其实就是传入的参数,也就是和int b = 10;  printf("this is test %d", b);的传入参数是一样的,只是一些每次打印日志都需要用到的东西被封装到了DEBUG_LOG();
  • 参照:LOG调试利器
#include <iostream>
#include <string>
#include <vector>
using namespace std;

#define _File_Save_ 0 
 
#define DEBUG_LOG(...) debug_log("DEBUG", __TIME__, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)

#if _File_Save_
void debug_log(
			const char *logLevel,
			const char *time,
			const char *file,
            const char *func,    
            const int   iLine,
            const char *format ,...)  // __VA_ARGS__会把传入的参数以逗号隔开并且匹配到const char *format ,...
{
		#include <stdarg.h>
 
		static char output[1024]={0};
        va_list arg_list;
        va_start(arg_list,format);
        vsnprintf(output,sizeof(output),format, arg_list);
        printf("[%s][%s][%s][%s][%d]:%s\n",time, logLevel, file, func, iLine, output);
        va_end(arg_list);
}

#else

void debug_log(
			const char *logLevel,
			const char *time,
			const char *file,
            const char *func,    
            const int   iLine,
            const char *format ,...)
{
		#include <stdarg.h>
 
		static char output[1024]={0};
        va_list arg_list;
        va_start(arg_list,format);
        vsnprintf(output,sizeof(output),format, arg_list);
 
		FILE *file_descrip = fopen("/home/zion/CPP-study/10.Skill/log.txt", "a+"); // 通过pwd来确认文件位置
        fprintf(file_descrip, "[%s][%s][%s][%s][%d]:%s\n",time, logLevel, file, func, iLine, output);
		fclose(file_descrip);
 
		va_end(arg_list);

}
#endif
int main()
{
	DEBUG_LOG("%s, ranking NO.%d", "You are so smart", 1); // 模仿printf的写法
 
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值