How to get the position of the function in the call stack?

351 views Asked by At

To give a background I want to visually print the log messages based on the call stack in a neat way.

For example.

Should give the output as

foo(){ 
    printf("Foo was called");
    bar();
}

bar(){
    printf("bar was called");
    jai();
}
jai(){
    printf("Jai was called");
}

<<< OUTPUT >>>
Foo was called.
   bar was called
      jai was called.

I don't want to pass the number of spaces as the argument to these function or maintain a global count of the same.

I was thinking that if we can get the position of the function in the call stack then we can fill in the same number of spaces before the text to get the required format of output.

I see backtrace function call provides that with the whole stack name returned as well. It returns the total number of functions in the call as well.

Is there any functions that returns the position only ?

2

There are 2 answers

0
Employed Russian On

It returns the total number of functions in the call as well.
Is there any functions that returns the position only ?

They are one and the same.

If the call stack is:

main -> foo -> bar -> jai

and you want to know that jai is 4 levels deep, then total number of functions is the level of jai.

If you want to ignore main and only count "your" functions, subtract 1 from total number of functions.

0
Basile Starynkevitch On

I would suggest to use existing libraries for that.

If all (or at least most) of your code is compiled with debugging information* in DWARF format (on Linux), I recommend Ian Taylor's libbacktrace (used inside GCC, but usable independently). When DWARF debug info is available, it is even able to give source location information...

You could also use the GNU glibc backtrace functions.

See also the return address builtins of GCC.

Note *: You can pass both -g and -O2 to the gcc or g++ compiler to have both debugging information and optimization enabled.