Wrapping C ++ functions using the GNU linker

I like the functionality of the GNU linker to greatly wrap functions. I usually use this, for example, non-deterministic 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 enclose a call in rand using the GNU linker link function:

 //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 a way to do the same with regular C ++ functions? The following does not work, I think this is due to the distortion of the name. But even when I try this with a distorted 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 
+6
source share
2 answers

You need to either extern "C" function you want to wrap (if possible), or you need to wrap a malformed name, for example, __wrap__Z3foov , and then pass --wrap=_Z3foov to the linker.

The correct underline is a little more complicated. This works for me:

 $ cat x.cc #include <iostream> using namespace std; int giveMeANumber(); int main() { cerr << giveMeANumber() << endl; return 0; } $ cat y.cc int giveMeANumber() { return 0; } extern "C" int __wrap__Z13giveMeANumberv() { return 10; } $ g++ -c x.cc y.cc && g++ xo yo -Wl,--wrap=_Z13giveMeANumberv && ./a.out 10 
+8
source

You seem to be trying to make fun of functions and classes for testing. Do you consider using Google Mock

+1
source

Source: https://habr.com/ru/post/903201/


All Articles