gcc 6.3 的手册页说:
--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
正确使用?