是否有一种简单的方法来指定要使用的替代函数(链接器)而不是标准函数?
我有一个围绕打开/关闭/读/写系统函数的包装器。我可以相对轻松地测试这些功能的良好路径的功能。
但是测试潜在的错误更难。为此,我需要进行打开/关闭/读取/写入操作,以便为每个测试生成特定的错误代码。有没有一种方法可以链接这些函数的替代版本,然后我可以编程以在返回之前设置适当的 errno 值?
最佳答案
链接器选项 --wrap
就是为了这个目的。
一些调用open
的代码:-
main.c
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#define N 32
int main(int argc, char *argv[])
{
char buf[N] = {0};
int fd = open(argv[1],O_RDONLY);
read(fd,buf,N - 1);
puts(buf);
close(fd);
return 0;
}
为了简单起见,它是一个程序,但它不一定是。
使用真正的open
:
$ gcc -Wall -c main.c
$ gcc -o prog main.o
$ echo "Hello world" > hw.txt
$ ./prog hw.txt
Hello world
您的替代open
必须称为__wrap_open
,并且
必须引用真正的open
,如果需要的话,如__real_open
:
dbg_open.c
#include <stdio.h>
extern int __real_open(const char *path, int oflag);
int __wrap_open(const char *path, int oflag)
{
printf("In tester %s\n",__FUNCTION__);
return __real_open(path,oflag);
}
无需重新编译main.c
即可将prog
中的open
替换为__wrap_open
;只是
在 prog
main.o
$ gcc -Wall -c dbg_open.c
$ gcc -o prog main.o dbg_open.o -Wl,--wrap=open
$ ./prog hw.txt
In tester __wrap_open
Hello world
如果您的 __wrap_foo
替代方案需要淘汰 C++ 函数
foo
那么您需要获取 foo
的重整以在链接中指定
选项 --wrap=mangled-foo
。但是既然你想取消系统调用
您可以避免这种并发症。
关于c++ - g++/clang 覆盖特定函数的链接器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47040618/