Kristoffer Kristoffer - 4 months ago 8
C Question

Add unique code to start and end of function in c

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.

Answer

If You are using GCC, look at -finstrument-functions switch - see https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-finstrument-functions-1037 It basically calls user-defined function upon entering and leaving any called function. This has some advantages:

  • You don't have to modify Your functions at all.
  • Your code is called no matter how the function exitted (You can have any number of return in Your function and don't care)