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

标签 c++ c gcc mocking clang

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

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

最佳答案

看一下 GCC 中的检测函数。来自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).

关于c++ - 在编译时使用注释自动包装 C/C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30726075/

相关文章:

c++ - OpenGL 错误 1282 与 glEndList()

c++ - C++ make_shared 可以用在数组上吗?

c++ - 错误 : invalid conversion from 'unsigned char*' to 'const signed char*'

c++ - 在 C/C++ 中实现 JSON RESTful 服务的方法

c - 使用任意源 MAC 发送 ARP 回复

GCC,奇怪的整数提升方案

c++ - 在 C++ 错误中将数组作为参数传递

c - C编程中的段错误

强制转换为 union 字段会产生转换警告

c - gcc 的 __attribute__((packed))/#pragma pack 不安全吗?