Search code examples
c++ctrace

Automatic tracing of program execution


I would like to know if we can enable tracing in any C or C++ application.

For example, with a gcc option or a small tool, I will enable trace and either trace is printed on console or dumped to a file.

Since there are lots of files and function / classes, I don't want to start adding the trace prints manually.

If such tools are not available, next choice is use scripting and try to add at the trace printing.

strace is not much useful as it gives mainly the system calls.


Solution

  • To trace the function entry/exit, you can recompile your code with the option -finstrument-functions so that each time a function is invoked, a __cyg_profile_func_enter() function is called, and __cyg_profile_func_exit() is called when the function returns.

    You can implement those functions to trace the addresses on the called functions, and then use nm to convert the addresses into function names.

    EDIT: etrace does all this: it provides the source code for the __cyg_profile_func_enter() and __cyg_profile_func_exit() and functions that write the addresses to a named pipe and a Perl and a Python script to read the addresses and do the actual tracing with the function names and indentation.