使用GNU链接器来封装C ++函数 [英] Wrapping C++ functions with GNU linker

查看:219
本文介绍了使用GNU链接器来封装C ++函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢GNU链接器功能来包装函数很多。我通常使用它模拟例如非确定性函数调用像rand()。考虑下面的例子,我想为giveMeANumber写一个单元测试:

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;
}



我可以使用GNU链接器功能包装调用rand,如下:

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

有没有办法用同样的正常C ++函数?以下不工作,我想这是因为名字改造。但是,即使我用错误的名称尝试它也不起作用。

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

任何想法?

推荐答案

您还需要 extern C你想要换行的函数(如果可能的话),或者你需要换行的名字,例如 __ wrap__Z3foov code> - wrap = _Z3foov 到链接器。

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, e.g., __wrap__Z3foov and then pass --wrap=_Z3foov to the linker.

得到下划线有点棘手。这适用于我:

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

这篇关于使用GNU链接器来封装C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆