在编译时自动用注释包装C/ c++函数

Automatically wrap C/C++ function at compile-time with annotation

本文关键字:包装 c++ 函数 注释 编译      更新时间:2023-10-16

在我的C/c++代码中,我想注释不同的函数和方法,以便在编译时(或链接时)添加额外的代码。添加的包装代码应该能够检查上下文(被调用的函数,线程信息等),读/写输入变量,修改返回值和输出变量。

我如何用GCC和/或Clang做到这一点?

看一下GCC中的检测函数。From man gcc:

   -finstrument-functions
       Generate instrumentation calls for entry and exit to functions.  Just after function entry and just before function exit, the following profiling functions will be called with the address of the current function and its call site.  (On some platforms,
       "__builtin_return_address" does not work beyond the current function, so the call site information may not be available to the profiling functions otherwise.)
               void __cyg_profile_func_enter (void *this_fn,
                                              void *call_site);
               void __cyg_profile_func_exit  (void *this_fn,
                                              void *call_site);
       The first argument is the address of the start of the current function, which may be looked up exactly in the symbol table.
       This instrumentation is also done for functions expanded inline in other functions.  The profiling calls will indicate where, conceptually, the inline function is entered and exited.  This means that addressable versions of such functions must be available.  If
       all your uses of a function are expanded inline, this may mean an additional expansion of code size.  If you use extern inline in your C code, an addressable version of such functions must be provided.  (This is normally the case anyways, but if you get lucky
       and the optimizer always expands the functions inline, you might have gotten away without providing static copies.)
       A function may be given the attribute "no_instrument_function", in which case this instrumentation will not be done.  This can be used, for example, for the profiling functions listed above, high-priority interrupt routines, and any functions from which the
       profiling functions cannot safely be called (perhaps signal handlers, if the profiling routines generate output or allocate memory).