Tool to print out functions being called during run time?

cdebuggingtrace

I am looking for such kind of a tool on either Unix/Linux platform which can achieve:

  1. I have the source files and I compiled the application myself (the source code is in C, although I don't really think it matters here)
  2. I want to run this application while every function calls are printed/logged to a stdout/file

For example:

#include <stdio.h>
int square(int x) { return x*x; }
int main(void) {
    square(2);
}

And when I run this program it will print out

  • main
  • square

I understand that gdb can do this to some extent, or valgrind but they all do not do exactly what I want. I am just wondering if such a tool exist? Thanks.

Best Answer

Using gcov:

$ gcc -O0 --coverage square.c
$ ./a.out
$ gcov -i square.c
$ awk -F '[,:]' '$1 == "function" && $3 > 0 {print $3, $4}' square.c.gcov
1 square
1 main

(where the number is the number of times the function was called (we skip the ones that are never called with $3 > 0 in the awk part)).

That's typically used for code coverage (how much of the code is being tested). You could also use the gprof code profiling tool (typically used to figure out how much time is spent in various areas of the code):

$ gcc -O0 -pg square.c
$ ./a.out
$ gprof -b -P
            Call graph


granularity: each sample hit covers 2 byte(s) no time propagated

index % time    self  children    called     name
        0.00    0.00       1/1           main [7]
[1]      0.0    0.00    0.00       1         square [1]
-----------------------------------------------

Index by function name

   [1] square
Related Question