Run Code Before Every Function Call for a Class in C++

后端 未结 9 1243
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 13:08

I would like to run some code (perhaps a function) right before every function call for a class and all functions of the classes that inherit from that class. I\'d like to do t

9条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-15 13:15

    Using g++, you could use the option -pg for the respective compilation units, which makes the compiler generate a call to the function mcount at the start of every function. mcount is usually provided by profiling tools like gprof, but you can also implement it yourself. You should however make sure that

    • mcount has C linkage (and is not C++-style name-mangled), i.e. by implementing it as a C function and compiling with a pure C compiler like gcc.
    • the compilation unit containing mcount is not compiled with -pg.

提交回复
热议问题