How to add code at the entry of every function?

前端 未结 6 853
悲哀的现实
悲哀的现实 2020-12-05 15:03

I want to add some code before every function call to do some checking. The only way I know is:

#define SOME_CODE printf(\"doing something...\");

class test         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 15:30

    For gcc there's a similar solution to the MSVC one someone else posted as an answer:

    #include 
    int depth=-1;
    extern "C" {
        void __cyg_profile_func_enter (void *, void *) __attribute__((no_instrument_function));
        void __cyg_profile_func_exit (void *, void *) __attribute__((no_instrument_function));
        void __cyg_profile_func_enter (void *func,  void *caller)
        {
            depth++;
        }
    
    
        void __cyg_profile_func_exit (void *func, void *caller)
        {
            depth--;
        }
    }
    
    class Foo {
    public:
        void bar() {
            std::cout << "bar: " << depth << std::endl;
        }
    };
    
    int main() {
        Foo f;
        f.bar();
        return 0;
    }
    

    Compile with g++ -Wall -Wextra -finstrument-functions. Be careful not to call an instrumented function from within the instrument hooks though! (See the man page for ways of excluding things)

提交回复
热议问题