简体   繁体   English

使用GNU链接器包装C ++函数

[英]Wrapping C++ functions with GNU linker

I like the GNU linker functionality to wrap functions a lot. 我喜欢GNU链接器功能来包装很多函数。 I normally use it mock eg nondeterministic function calls like rand() . 我通常使用它来模拟例如rand()类的非确定性函数调用。 Consider the following example where I would like to write a unit test for giveMeANumber : 考虑以下示例,我想为giveMeANumber编写单元测试:

//number.cpp
int giveMeANumber() {
  return rand() % 6 + 1;
}

I can wrap the call to rand with the GNU linker functionality wrap like this: 我可以使用GNU链接器功能包装来调用rand,如下所示:

//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? 有没有办法对普通的C ++函数做同样的事情? 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

You need to either also extern "C" the function you want to wrap (if that's possible) or you need to wrap the mangled name, eg, __wrap__Z3foov and then pass --wrap=_Z3foov to the linker. 您还需要将要包装的函数(如果可能的话) --wrap=_Z3foovextern "C" ,或者您需要包含__wrap__Z3foov名称,例如__wrap__Z3foov ,然后将--wrap=_Z3foov传递给链接器。

Getting the underscores right is a little tricky. 获得正确的下划线有点棘手。 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++ x.o y.o -Wl,--wrap=_Z13giveMeANumberv && ./a.out
10

It seems like you are trying to mock functions and classes for testing. 看起来你正在尝试模拟函数和类进行测试。 Have you consider using Google Mock 您考虑过使用Google Mock吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM