title: Tracing of function calls in C
body: <p>I'm developing some modules for an automation system written in C and I need to perform lots of work with hardware. And I see no simple way (like traditional) to debugging things instead of trace logs. So I'm looking for a good practice to log function calls. At least the sequence of calls and return values.</p>
  
  <p>The way it is performed in application is quite straightforward and actually pollutes the code with irrelevant constructions like</p>
  
  <pre><code>int function (int param){
     if(trace_level &amp; LOG_FCALLS){
        writelog("Entering function()");
     }
  
     /* something useful */
  
     if(trace_level &amp; LOG_FCALLS){
        writelog("Exit from function()=%d", ret);
     }
  }
  </code></pre>
  
  <p>I decided to use a macro that will do all the dirty work. Now it looks like this</p>
  
  <pre><code>#define LOG_E(fn) const char *__fname=fn;  printf("LOG: Entry to %s\n",__fname)
  #define return(ret)     printf("LOG: Exit from %s()=%d\n",__fname,ret)
  
  int testFunc(){
     LOG_E("testFunc");
  
     /*do useful things */
  
     return(ret);
  }
  </code></pre>
  
  <p>I see the problems with this code</p>
  
  <ol>
  <li><p>I'm overriding return statement, and it is requires to write <code>return(ret)</code> all the time instead of <code>return ret</code>. It is easy to forget this issue.</p></li>
  <li><p>I'm defining string variable within my macro. I'm aware that <code>__func__</code> macro exists in C99, but my compiler, unfortunately, doesn't support this macro or any other relevant macros.</p></li>
  <li><p>How to log the values of function arguments?</p></li>
  </ol>
  
  <p>I'm pretty sure that it is not a new problem and I'm not the first one who faced with it. I'm also aware about AOP thing, but the code instrumentation is not acceptable solution for my system and I haven't found any possibility to do it with my compiler.</p>
  
  <p>So I'm looking for a good ideas how to implement tracing in the most elegant way.</p>
  
  <p>My environment:
  Legacy code, C, Watcom 10.x, real-time OS</p>