我有一个手工的C程序剖析运行在ARM嵌入系统这是一个“侵入性”的,这意味着每当我想分析一个函数时,我需要在函数的开头和结尾添加一些代码,比如:
int f(int a, int b) {
BeginProfiling("f");
...
EndProfiling();
}
我想知道有没有更好的办法我是说,如果我使用Python,我肯定会使用decorator有没有更好的解决方案可以使用C宏来拥有一个类似decorator的寄存器机制我希望代码如下:
__PROFILING__
int f(int a, int b) {
...
}
最佳答案
#include <stdio.h>
#define PROFILE2(fun, a, b) mkprofile2args(#fun, fun, a, b)
typedef int (*signature2args) (int, int);
void
profiler_begin(char const*m)
{
printf("START %s\n", m);
}
void
profiler_end(char const*m)
{
printf("END %s\n", m);
}
int
mkprofile2args(const char* m, signature2args fun, int a, int b)
{
profiler_begin(m);
int res = fun(a, b);
profiler_end(m);
return res;
}
int
function_add(int a, int b)
{
return a+b;
}
#define function_add(a, b) PROFILE2(function_add, a, b)
void
main(void)
{
printf("%d\n", function_add(10, 20));
}
#undef function_add
关于c - C语言:如何使用宏作为装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45583824/