zoukankan      html  css  js  c++  java
  • C++日志之获取函数的名字,行号,文件名

    在后台程序运行出问题时,详尽的日志是抓错不可缺少的帮手,这里提供一个能自动记录日志触发点文件名、行号、函数名的方法,关键是利用C99新增的预处理标识符__VA_ARGS__

    先介绍几个编译器内置的宏定义,这些宏定义不仅可以帮助我们完成跨平台的源码编写,灵活使用也可以巧妙地帮我们输出非常有用的调试信息。


    ANSI C标准中有几个标准预定义宏(也是常用的):

    __LINE__:在源代码中插入当前源代码行号;

    __FILE__:在源文件中插入当前源文件名;

    __DATE__:在源文件中插入当前的编译日期

    __TIME__:在源文件中插入当前编译时间;

    __STDC__:当要求程序严格遵循ANSI C标准时该标识被赋值为1;

    __cplusplus:当编写C++程序时该标识符被定义。

    代码:

    #define LOG(level, format, ...) /
        do { /
            fprintf(stderr, "[%s|%s@%s,%d] " format "/n", /
                level, __func__, __FILE__, __LINE__, ##__VA_ARGS__ ); /
        } while (0)
    
    int main()
    {
        LOG(LOG_DEBUG, "a=%d", 10);
        return 0;
    }
    

    运行结果:
    [DEBUG|main@a.c,17] a=10

      

    限制是format不能是变量,必须是常量字符串,如果要记录一个变量字符串,不能像printf那样printf(s)了,要LOG("DEBUG", "%s", s)。

    另外还有一种:

    //============================================================================
    // Name : debug.cpp
    // Author : boyce
    // Version : 1.0
    // Copyright : pku
    // Description : Hello World in C++, Ansi-style
    //============================================================================
    #include <stdio.h>
    
    #define __DEBUG__
    
    #ifdef __DEBUG__
    #define DEBUG(format,...) printf("File: "__FILE__", Line: %05d: "format"
    ", __LINE__, ##__VA_ARGS__)
    #else
    #define DEBUG(format,...)
    #endif
    
    int main(int argc, char **argv) {
        char str[]="Hello World";
        DEBUG("A ha, check me: %s",str);
        return 0;
    }
    

      

  • 相关阅读:
    写一点应用关于 Lucene.Net,snowball的重新组装(三)
    写一点应用关于 Lucene.Net,snowball的重新组装(二)
    C++ stirng,int 互转(转载)
    特征词选择算法对文本分类准确率的影响(二)
    webGL简单例子(klayge)
    QT 信号和槽
    windows资源管理(内核对象/GDI对象/user对象)
    memcpy memmove区别和实现
    演示软件SpringHome制作
    在浏览器中加载googleEarth插件
  • 原文地址:https://www.cnblogs.com/cthon/p/9193378.html
Copyright © 2011-2022 走看看