gpt4 book ai didi

c - C语言:如何使用宏作为装饰器?

转载 作者:太空宇宙 更新时间:2023-11-04 00:00:48 24 4
gpt4 key购买 nike

我有一个手工的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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com