I like the GNU linker functionality to wrap functions a lot. I normally use it mock e.g. nondeterministic function calls like rand(). Consider the following example where I would like to write a unit test for giveMeANumber:
//number.cpp
int giveMeANumber() {
return rand() % 6 + 1;
}
I can wrap the call to rand with the GNU linker functionality wrap like this:
//test.cpp
extern "C" int __wrap_rand(void) {
return 4;
}
void unitTest() {
assert giveMeANumber() == 5;
}
$ g++ test.cpp -o test number.o -Xlinker --wrap=rand
Is there any way to do the same with normal C++ functions? The following does not work, I guess it is because of name mangling. But even when I try it with the mangled name it does not work.
//number.cpp
int foo() {
//some complex calculations I would like to mock
}
int giveMeANumber() {
return foo() % 6 + 1;
}
//test.cpp
extern "C" int __wrap_foo(void) {
return 4;
}
$ g++ test.cpp -o test number.o -Xlinker --wrap=foo
Any ideas?