Gcc: adding automatic debug information during compilation

201 views Asked by At

I was asked to implement a kind of gcc plug-in. Basically what I have to do is to add some debugging code in order to add debugging information to the written code.

Let's use an example in order to explain what I need. Suppose we have the following function

int factorial(int n){
  //printf("Factorial called arg n : %d", n);
  if (n==0 || n == 1){
    //printf("Factorial returned with value %d", 1);
    return 1;
  }
  else{
    int ret = n * factorial(n-1);
    //printf("Factorial returned with value %d", ret);
    return ret;
  }
}

now what I would like to get after the execution is the trace of the function, I mean I need to print out the parameter value received in each call and the return value. For instance, if I execute factorial(4) I expect the following output:

  • Factorial called arg n : 4
  • Factorial called arg n : 3
  • Factorial called arg n : 2
  • Factorial called arg n : 1
  • Factorial returned with value 1
  • Factorial returned with value 2
  • Factorial returned with value 6
  • Factorial returned with value 24

So, what I need is this output for all the functions in the piece of code compiled. I do not know if I made me understand but the key point is that I want to avoid adding this debugging information by hand but by the compilation step. I was suggested to use MELT and I am giving my first tries with it but I was wondering if there are some others options. All kind of comments or suggestions are welcomed.

1

There are 1 answers

2
PersianGulf On

You can use MACROs:

int factorial(int n){
        #ifdef MYMACRO
        printf("Factorial called arg n : %d\n", n);
        #endif
        if (n==0 || n == 1){
                #ifdef MYMACRO
                printf("Factorial returned with value %d\n", 1);
                #endif
                return 1;
        }
        else{
                int ret = n * factorial(n-1);
                #ifdef MYMACRO
                printf("Factorial returned with value %d\n", ret);
                #endif
                return ret;
        }
}

When you want to compile it:

gcc -DMYMACRO myprog.c

And when you don't show output:

gcc myprog.c