title: Mocking library functions in C
body: <p>I want to mock functions of the c lib such as <code>malloc</code> without altering too much the original source file (the one that uses malloc).</p>
  
  <p>I tried including a header file "mock.h" like</p>
  
  <pre><code>#ifndef MOCK_H_
  # define MOCK_H_
  # ifdef MOCK_MODE
  
  #  include &lt;sys/types.h&gt;
  
  extern void *my_mock_malloc(size_t n);
  void    *malloc(size_t n) __attribute__((weak, alias ("my_mock_malloc")));
  
  # endif /* MOCK_MODE */
  #endif /* !MOCK_H_ */
  </code></pre>
  
  <p>but it gives me an error</p>
  
  <pre><code>in file included from ...:
  /usr/include/stdlib.h:466:14: error: ‘malloc’ aliased to undefined symbol ‘my_mock_malloc’
   extern void *malloc (size_t __size) __THROW __attribute_malloc__ __wur;
  </code></pre>
  
  <p><a href="https://stackoverflow.com/questions/7649979/gcc-alias-to-function-outside-of-translation-unit-aka-is-this-even-the-right-t">GCC alias to function outside of translation unit -AKA- is this even the right tool for the job?</a> gives a partial solution: using the linker I create an alias on a symbol. I can now compile with <code>-Xlinker --defsym "malloc"="my_mock_malloc"</code>. The problem is that all my <code>.o</code> files are linked using this option and thus the unit testing framework I use (<a href="http://check.sourceforge.net/" rel="nofollow noreferrer">check</a>) is affected by the mocking (and thus it receives is SIGSEGV when I make my mock function return <code>NULL</code>).</p>
  
  <p>Is there a way to perform such symbol aliasing locally, so I can make my tesing framework use the real malloc? Os is there a better solution than this one?</p>