Mocking C functions in MSVC (Visual Studio)
<p>I am reading several articles on mocking C functions (like <a href="http://www.throwtheswitch.org/cmock/" rel="nofollow">CMock</a>, or <a href="https://lwn.net/Articles/558106/" rel="nofollow">CMocka</a>), but I am not sure how the actual functions are replaced with mocked functions in this process. For example, CMocka relies on automatic wrapping using a GNU compiler, which supports parameters like <code>--wrap</code> to append the <code>__wrap</code> prefix to function calls, or <em>weak symbols</em> which allow you to override any symbol you like.</p>

<p>But how do you do this in Visual Studio, for pretty much all other frameworks?</p>

<p>For example, <a href="http://www.throwtheswitch.org/cmock/" rel="nofollow">CMock has an example</a> similar to this (simplified a lot here):</p>

<pre><code>// myfunc.c
#include &lt;parsestuff.h&gt;

// this is the function we would like to test
int MyFunc(char* Command)
{
    // this is the call to the function we will mock
    return ParseStuff(Command);
}
</code></pre>

<p>There is also the actual implementation, which contains the actual function the linker should find in the actual application:</p>

<pre><code>// parsestuff.c

int ParseStuff(char* cmd)
{
    // do some actual work
    return 42;
}
</code></pre>

<p>Now, during testing the Ruby script creates mock functions like:</p>

<pre><code>// MockParseStuff.c (auto created by cmock)

int ParseStuff(char* Cmd);
void ParseStuff_ExpectAndReturn(char* Cmd, int toReturn);
</code></pre>

<ol>
<li><p>But if the VS project already includes <code>parsestuff.c</code>, how will it be possible that the call from <code>myfunc.c</code> ends up in <code>MockParseStuff.c</code>?</p></li>
<li><p>Does this mean I cannot have <code>parsestuff.c</code> included in the unit testing project? But if this is the case, then it's also impossible to mock, for example, <code>MyFunc</code> from <code>myfunc.c</code> in any tests, since I already had to include the file it in order to test it?</p></li>
</ol>

<p><strong>(Update)</strong> I am also aware that I can include the <code>.c</code> file instead of the <code>.h</code> file, and then do some preprocessor stuff to replace the original call, like:</p>

<pre><code>// replace ParseStuff with ParseStuff_wrap
#define ParseStuff ParseStuff_wrap
// include the source instead of the header
#include &lt;myfunc.c&gt;
#undef ParseStuff

int ParseStuff_wrap(char* cmd) 
{
    // this will get called from MyFunc,
    // which is now statically included
}
</code></pre>

<p>but this seems like a lot of plumbing, and I don't even see it mentioned anywhere.</p>