Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically running code at the start of every C function

I have an almost identical question as How to add code at the entry of every function? but for C:

As I'm maintaining someone else's large undocumented project, I wish to have code similar to

static C0UNT_identifier_not_used_anywhere_else = 0;
printf("%s%s:%d#%d", __func__, strrchr(__FILE__,'/'), __LINE__, ++C0UNT_identifier_not_used_anywhere_else);

to run on entry of every function, so that I

  1. have a log of what calls what, and
  2. can tell, on which nth call to a function it breaks.

The existing code comprises hundreds of source files, so it is unfeasible to put a macro e.g.

#define ENTRY_CODE ...
...
int function() {
  ENTRY_CODE
  ...
}

in every function. I am also not using DevStudio, Visual Studio or other compiler providing __cyg_profile_func_enter or such extensions.

Optionally, I'd like to printf the return value of each function on exit in a similar style. Can I do that too?

like image 857
Gnubie Avatar asked Dec 13 '11 14:12

Gnubie


People also ask

Does main function run first?

In C it is function main. But the program starts executing before the call to the main. That before main code prepares the execution environment for your program and it is called a startup code.

What happens before main () is called in C?

The _start Function. For most C and C++ programs, the true entry point is not main , it's the _start function. This function initializes the program runtime and invokes the program's main function.

How are functions executed in C?

The execution of a C program begins from the main() function. And, the compiler starts executing the codes inside functionName() . The control of the program jumps back to the main() function once code inside the function definition is executed. Note, function names are identifiers and should be unique.

Is it possible to execute code even after the program exits the main () function in C?

No, it is not possible. When the main method exists, the program terminates.


1 Answers

Since you have tagged with gcc it has the -finstrument-functions option:

Generate instrumentation calls for entry and exit to functions. ...

like image 155
Jens Gustedt Avatar answered Sep 23 '22 17:09

Jens Gustedt