3
GCC 6.3的手册页说:如何正确使用`--wrap`选项来包装函数?
--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
嗯,我不明白。上面的例子的输出对我来说似乎是错误的。'foo()'应该输出''wrap foo' ! 我究竟做错了什么? – eDeviser
您忽略了“未定义参考”**要求**。 – StoryTeller