gpt4 book ai didi

c - 如何使用预处理器获取函数签名并声明另一个具有相同签名的函数?

转载 作者:行者123 更新时间:2023-12-04 12:16:45 29 4
gpt4 key购买 nike

如何使用预处理器获取一个函数签名并声明另一个具有相同签名的函数?

我想做这样的事情:

int function_to_be_copied_from(int arg, int arg2);
FUNC_COPY_SIGNATURE(function_to_be_copied_from, new_function_name)
{
do_something(arg, arg2);
}

得到这个:

int function_to_be_copied_from(int arg, int arg2);
int new_function_name(int arg, int arg2)
{
do_something(arg, arg2);
}

Gcc 扩展是允许的,例如 typeof

我想创建一个运行时分析器系统,具体来说,我需要使用宏替换函数。这个宏必须创建一个包装函数来计算被替换函数的执行时间并重命名被替换函数。

最佳答案

尝试以下方法:

创建用于分析的宏:

#define profile_me(my_code) ({timer_start_code; my_code timer_stop_code;})
// NOTE: there is no `;` after my_code in macro evaluation
// This helps for profiling any code, having braces. (see Sample_usage2)
// Sample_usage1: profile_me(function_to_be_copied_from(5,10););
// Sample_usage2: profile_me(if(condition){do_something();});

为要分析的函数创建一个递归宏:

#define function_to_be_copied_from(...) profile_me \
(function_to_be_copied_from(__VA_ARGS__);)

然后正常使用原来的功能。分析代码将被自动调用。

为了处理返回值:

#define profile_me_int(my_code) ({       \
int ret; \
timer_start_code; \
ret = my_code \
timer_stop_code; \
ret; \
}) // ret data type is chosen based on function_to_be_copied_from's return type

#define function_to_be_copied_from(...) profile_me_int \
(function_to_be_copied_from(__VA_ARGS__);)

关于c - 如何使用预处理器获取函数签名并声明另一个具有相同签名的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23391367/

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