Reputation: 2967
How can I get a function signature and declare another with the same signature using the preprocessor?
I wanted to do something like this:
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);
}
And get this:
int function_to_be_copied_from(int arg, int arg2);
int new_function_name(int arg, int arg2)
{
do_something(arg, arg2);
}
Gcc extensions are allowed, such as typeof
, for example.
I want to create a runtime profiler system, specifically, I need to replace functions using a macro. This macro has got to create a wrapper function that computes the execution time of the replaced function and rename the replaced function.
Upvotes: 3
Views: 130
Reputation: 20980
Try below approach:
Create a macro for profiling:
#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();});
Create a recursive macro for the functions you want to profile:
#define function_to_be_copied_from(...) profile_me \
(function_to_be_copied_from(__VA_ARGS__);)
Then use the original function normally. The profiling code will be called automatically.
For taking care of the return value:
#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__);)
Upvotes: 2