For unit testing I'd like to replace a function from "outside". Normally, I'm using the wrapping mechanism - but unfortunately this does not work for calls to the function from within the same compilation unit.
My idea was to mark the function as "weak" so I am able to reimplement it in a testing application. Generally this works using the following code:
File myfunctions.c (this is the code under test):
#include "myfunctions.h"
int weakFunction(int param) __attribute__((weak));
int weakFunction(int param)
{
return 2*param;
}
int myfunction(int param)
{
int result = weakFunction(param);
return (result == (2*param)) ? 1:0;
}
File main.c
#include "myfunctions.h"
int weakFunction(int param)
{
return 3*param;
}
int main()
{
return myfunction(5);
}
This example works as expected - when I remove weakFunction
from main.c, the program returns 1, when I add weakFunction
the program returns 0. Looks good at this point.
But as soon as I change the order within myfunctions.c as follows, the resulting program crashes with a segmentation fault:
File myfunctions.c (modified order):
#include "myfunctions.h"
int weakFunction(int param) __attribute__((weak));
int myfunction(int param)
{
int result = weakFunction(param);
return (result == (2*param)) ? 1:0;
}
int weakFunction(int param)
{
return 2*param;
}
Any idea? What could be the reason for the crash?
I am using GCC 4.8.1 (MinGW w64 build) on Windows 7.
Thanks for any help! Florian