3

I want to write a debug printing function that prints LINE, FILE, func and some other stuff. The twist is that I'd like to automatically indent the printouts according to their depth in the call stack, so something like

main.c:55:main()
   functions.c:33:function1()
   functions.c:133:function2()
      functions.c:33:function1()
      functions.c:33:function1()

if function1 returns immediately, and function2 calls function1 twice.

I guess this could be done by using a global variable which is manually incremented each time a function is called and decremented whenever it is returned, but this would require quite the code base rehaul. I was wondering if there was an easier way to do it?

I don't mind if the solution is non-standard C, so long as it is standard GNU.

1
  • Tip: Instill some control to limit the height up the stack that code searches as the stack could be very deep. Commented Apr 20, 2017 at 17:55

1 Answer 1

4

You can probably do this with the code profiling options in Gcc. https://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Code-Gen-Options.html

-finstrument-functions
Generate instrumentation calls for entry and exit to functions. Just after function entry and just before function exit, the following profiling functions will be called with the address of the current function and its call site. (On some platforms, __builtin_return_address does not work beyond the current function, so the call site information may not be available to the profiling functions otherwise.)

void __cyg_profile_func_enter (void *this_fn,
                               void *call_site);
void __cyg_profile_func_exit  (void *this_fn,
                               void *call_site);
Sign up to request clarification or add additional context in comments.

1 Comment

That's great! If I understand it correctly, GCC only provides the prototypes and it's up to the user to implement them in whatever way he/she chooses?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.