Reputation: 486
I am looking for a way to automatically add code to the start and the beginning of a function. The idea being that i want to profile the running code later. For example i have the functions:
void helloWorld(){
printf("Hello World!\n");
}
void worldHello(){
printf("World hello!\n");
}
I would like to have some kind of macro that expands them to:
void helloWorld(){
printf("Function id 1 enter");
printf("Hello World!\n");
printf("Function id 1 exit");
}
void worldHello(){
printf("Function id 2 enter");
printf("World hello!\n");
printf("Function id 2 exit");
}
Where the id is uniquely given each time i use my macro. Do anyoen have any good idea on how i could achieve this? i looked at the "__COUNTER__" in GCC but didnt really get it working as i wanted to.
Upvotes: 3
Views: 2710
Reputation: 4239
If You are using GCC, look at -finstrument-functions
switch - see https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-finstrument-functions It basically calls user-defined function upon entering and leaving any called function. This has some advantages:
return
in Your function and don't care)Upvotes: 4
Reputation: 436
It may be more descriptive to use __func__ rather than __COUNTER__. Here is an example implementation of a macro that does what you want.
#include <stdio.h>
#define WRAPPED_FUNC(funcname, ...) \
funcname { \
printf("Function %s entered\n", __func__); \
__VA_ARGS__ \
printf("Function %s exited\n", __func__); \
}
WRAPPED_FUNC(
void helloWorld(),
{
printf("Hello World!\n");
}
)
WRAPPED_FUNC(
void worldHello(),
{
printf("World hello!\n");
}
)
int main() {
helloWorld();
worldHello();
return 0;
}
Upvotes: 1
Reputation: 349
you can use the functions name instead of a number as ID. since function name is unique. for example you can use the macros:
#define START printf( "%s:%d Start \n", __func__, __LINE__)
#define END printf("%s:%d End \n", __func__, __LINE__)
or in kernel:
#define START pr_err(KBUILD_MODNAME ":%s:%d start \n", __func__, __LINE__)
#define END pr_err(KBUILD_MODNAME ":%s:%d end\n", __func__, __LINE__)
Upvotes: 3