title: Function mocking (for testing) in C?
body: <p>I would like to write tests for a C library, in C.  I'd like to mock out some functions for the test.</p>
  
  <p>Suppose my library is compiled from the following source:</p>
  
  <pre><code>/* foo.h */
  int myfunction(int x, int y);
  
  /* foo.c */
  #include "foo.h"
  
  static int square(int x) { return x * x; }
  
  int myfunction(int x, int y) {
      return square(x) + square(y);
  }
  </code></pre>
  
  <p>I want to write a test like this:</p>
  
  <pre><code>/* foo_test.c */
  #include "foo.h"
  
  static int square(int x) { return x + 1; }
  
  int main(void) {
      assert(myfunction(0, 0) == 2);
      return 0;
  }
  </code></pre>
  
  <p>Is there any way I can compile so that <code>myfunction</code> will use the definition of <code>square</code> in <code>foo_test.c</code>, instead of the one in <code>foo.c</code>, only when linking the executable <code>foo_test</code>?  That is, I want to compile <code>foo.c</code> into a library (let's call it <code>libfoo.so</code>), and then compile <code>foo_test.c</code> with <code>libfoo.so</code> and some magic so that I'll get an executable <code>foo_test</code> which uses the different implementation of <code>square</code>.</p>
  
  <p>It would be helpful to hear solutions for when <code>square</code> is not declared <code>static</code>, but solving the above case would be even better.</p>
  
  <p>EDIT: It seems hopeless, but here's an idea: Suppose I compile with <code>-O0 -g</code> so it's unlikely that <code>square</code> will get inlined and I should have symbols showing where the call was resolved.  Is there a way to sneak into the object file and swap out the resolved reference?</p>