capturing enter and exit of every function

If I have a "Hello World" function (just prints that) and a similar "Goodbye World" function... is there a way (maybe a compiler option?) that I can get them to be executed directly as the absolute first and last things run in every function call.

So for example, the following code:

int foo()
{
cout << "I think therefor I am" << endl;
return 0;
}

should print out:

I assume from this model, that a simple find&replace would work, even using something like grep/sed to add a call to hello() as the first call, and a goodbye() as the last thing before any return/function-exit... but is this doable without manually (including a sed script as "manual") modifying the code? IE, is there a pre-call/post-call function wrapper?...

IF this is exactly what you want - no - manual is your only option. But since that has almost no real world use - are you looking to instrument your code somehow? profiling?

You can also literally write a single generic wrapper that calls each function that takes a function pointer as an argument:

  1. hello()
  2. function pointer call to selected funtion
  3. foo()

then in your code call generic(function1); generic(function5); etc.

You can actually use a sed script to replace lines beginning with "{" and "}" with preprocessor directives:

#define FBEGIN {
#define FEND }

Now the sed scripts:

sed -i 's/^{$/FBEGIN/' *.c
sed -i 's/^}$/FEND/' *.c

Compile and make sure it works. Once it does, you can change your macros so that FBEGIN and FEND call a function too, like something that logs to a file:

#define FBEGIN { fprintf(stderr,"%s:%d: Entering function\n",__FILE__,__LINE__);

See this post on instrumenting code - Perret Yannick - Re: How to use '-finstrument-functions' in C++ programs ?.

That's awesome.

Here is a good article on how to do it - including using graphviz to visualize the output.

Visualize function calls with Graphviz