How to tell gcc to instrument the code with calls to my own function each _line_ of code?

前端 未结 4 1972
你的背包
你的背包 2020-12-19 12:26

For example, there is the source:

void my_special_debugging_function(const char* function_name, const char* file_name, int line_number);

void func1() {
             


        
相关标签:
4条回答
  • 2020-12-19 12:45

    As stated in the other answer, I don't think that there is any way to tell GCC to do that, without preprocessor tricks and edits to the source code. – nategoose

    0 讨论(0)
  • 2020-12-19 12:48

    If you are using a gcc version >=4.5 you can write a gcc plugin that processes the AST in the way you like. But that solution would be compiler dependent.

    You can also obtain AST from eclipse CDT and regenerate C code from that input.

    0 讨论(0)
  • 2020-12-19 12:53

    See -finstrument-functions in the GCC documentation. You may want to use dladdr() in the debugging function, which may also require linking with -Wl,-export-dynamic.

    0 讨论(0)
  • 2020-12-19 12:59

    You can do it easily using aspectc++. Get this compiler from aspectc.org Here is a simple aspect which serves your requirements. Trace.ah

    #ifndef __trace_ah__
    #define __trace_ah__
    #include <cstdio>
    #include <iostream>
    using namespace std;
    template <int I> struct ArgPrinter
    {
    template <class JP> static inline void work (JP &tjp) {
    ArgPrinter<I - 1>::work (tjp);
    cout << *tjp.template arg<I - 1> () << " ";
    }
    };
    template <> struct ArgPrinter<0>
    {
     template <class JP> static inline void work (JP &tjp) {}
    };
    
    
    aspect trace {
    int depth=-1;
    pointcut virtual methods() = "% ...::%(...)";
    
    template <class JP> void print_args (JP &tjp)
        {
             ArgPrinter<JP::ARGS>::work (tjp);
        }
    
    advice execution (methods()) : before ()
    {
        depth++;
        cout << "Enter -> " << JoinPoint::signature() <<" Depth:"<<depth<< " ARGS " << JoinPoint::ARGS <<" (";
        tjp->arg(0);
        print_args (*tjp);
        cout<<")"<<endl;
        cout<< "console--"<<endl;
    }
    
    advice execution("% ...::%(...)" && !"void ...::%(...)") : after()
    {
        cout<< "--console"<<endl;
        JoinPoint::Result res = *tjp->result();
        cout << "Exit <- " << tjp->signature()<< " Depth: "<<depth<< " RET " << res<<endl;
        depth--;
    }
    advice execution("void ...::%(...)") : after()
    {
        cout<< "--console"<<endl;
        cout << "Exit <- " << tjp->signature()<< " Depth: "<<depth<< " RET void"<<endl;
        depth--;
    }
    };
    #endif
    

    Compile this aspect with your project using ac++ compiler then run your program. Then you should see the trace in the console. Happy Tracing!

    0 讨论(0)
提交回复
热议问题