title: How to implement decorators in C and C++
body: <p>I have a situation in C as well as in C++ which can be best solved with something like the Python like decorators: I have few a functions which I'd like to wrap around with something else so that before the function enters some statements are performs and when it leaves some other functionality is executed.</p>
  
  <p>For instance, I have a few functions in a library C file which when called should lock a semaphore and before returning the control to callee, should release the semaphore. without the lock they have following structure:</p>
  
  <pre><code>int f1(int)
  {
      ...
      ... 
  }
  
  int f2(char*)
  {
      ....
  }
  
  int f3(blabla)
  {
      ....
  }
  
  ... fn(...)
  </code></pre>
  
  <p>I'd like to define a global semaphore which should be locked before each of these functions is called and released when the function is returned. I'd like to do it with as much simplicity as possible; something close to this:</p>
  
  <pre><code>#lockprotected
  int f1(int)
  {
     ... /* nothing changed over here */
  }
  #endlockprotected
  </code></pre>
  
  <p>or something like</p>
  
  <pre><code>int f1(int)
  {
     ... /* nothing changed over here */
  }
  #lockprotected f1
  </code></pre>
  
  <p>What I don't want is:</p>
  
  <ol>
  <li>Change the function names as they are library functions and are being called from many places.</li>
  <li>Explicitly place any statement before return calls as most of the functions have many early returns in between. Or for that matter change any internals of the function.</li>
  </ol>
  
  <p>What would be the most elegant way?</p>