gcc 6.3 的 man 手册中写道:
--wrap=symbol
Use a wrapper function for symbol. Any undefined reference to
symbol will be resolved to "__wrap_symbol". Any undefined
reference to "__real_symbol" will be resolved to symbol.
...
If you link other code with this file using --wrap malloc, then all
calls to "malloc" will call the function "__wrap_malloc" instead.
The call to "__real_malloc" in "__wrap_malloc" will call the real
"malloc" function.
所以我创建了一个简单的示例:
#include <stdio.h>
int foo() {
printf("foo\n");
return 0;
}
int __wrap_foo() {
printf("wrap foo\n");
return 0;
}
int main () {
printf("foo:");foo();
printf("wrapfoo:");__wrap_foo();
printf("realfoo:");__real_foo();
return 0;
}
并使用以下命令进行编译:
gcc main.c -Wl,--wrap=foo -o main
这给了我一个警告:
main.c:18:21: warning: implicit declaration of function ‘__real_foo’ [-Wimplicit-function-declaration]
printf("realfoo:");__real_foo();
^~~~~~~~~~
好的,继续前进。现在我建议输出结果应该像这样:
foo:wrap foo
wrapfoo:wrap foo
realfoo:foo
相反我得到了这个:
foo:foo
wrapfoo:wrap foo
realfoo:foo
希望问题已经清楚了。我对这个警告感到困惑。通常,链接器应该将__real
函数链接到foo()
。此外,对foo()
的调用应该链接到__wrap_foo
。但是输出显示,实际执行的是foo()
。
如何正确使用--wrap
?
foo
已经存在,对foo
的调用不会造成对foo
的未定义引用。 - StoryTeller - Unslander Monicafoo()
应该输出"wrap foo"
!我做错了什么? - eDeviser--wrap
来创建一些存根和模拟对象,当没有其他选择来实现一些单元测试时。 - eDeviser