how to trace function call in C?

后端 未结 8 1682
遇见更好的自我
遇见更好的自我 2020-12-02 13:45

Without modifying the source code, how can i trace which functions are called and with what parameters, when some function(say func100 in the following example) is in

相关标签:
8条回答
  • 2020-12-02 14:33

    You can look into log4cxx, a project hosted by the apache foundation. I know that log4j, the java variant allowed you to set the sensitivity, and you could track every single thing that was done in the program. Maybe that the c++ variant is the same, but there are several alternatives-there's an aspect oriented c++ compiler, and you can define an aspect across all functions, and have it catch and print the variables. Another alternative is to use a debugger.

    To summarize: debugger, log4cxx or AOP

    0 讨论(0)
  • 2020-12-02 14:34

    With the GNU C Library, you can use the backtrace module. Here is an example for that:

    #include <stdio.h>
    #include <execinfo.h>
    #include <stdlib.h>
    
    
    void handler(char *caller) {
      void *array[10];
      size_t size;
      printf("Stack Trace Start for %s\n",caller);
      size = backtrace(array, 10);
      backtrace_symbols_fd(array, size, 2);
      printf("Stack Trace End\n");
    }
    
    void car() {
        handler("car()");
        printf("Continue Execution");
    }
    void baz() {car(); }
    
    void bar() { baz(); }
    void foo() { bar(); }
    
    
    int main(int argc, char **argv) {
      foo(); 
    }
    

    compile with -g -rdynamic compiler option to load the symbols

    gcc -g -rdynamic Test1.c -o Test
    

    You will see an output similar to

    Stack Trace Start for car()
    ./Test(handler+0x2d)[0x80486f1]
    ./Test(car+0x12)[0x804872e]
    ./Test(baz+0xb)[0x8048747]
    ./Test(bar+0xb)[0x8048754]
    ./Test(foo+0xb)[0x8048761]
    ./Test(main+0xb)[0x804876e]
    /lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xe7)[0x126e37]
    ./Test[0x8048631]
    Stack Trace End
    Continue Execution in car
    

    You can write this handler function and call from anywhere in your program at any number of time. Remember to increase the array size as required.

    0 讨论(0)
提交回复
热议问题