c++ - g++/clang 覆盖特定函数的链接器

标签 c++ linker g++ clang

是否有一种简单的方法来指定要使用的替代函数(链接器)而不是标准函数?

我有一个围绕打开/关闭/读/写系统函数的包装器。我可以相对轻松地测试这些功能的良好路径的功能。

但是测试潜在的错误更难。为此,我需要进行打开/关闭/读取/写入操作,以便为每个测试生成特定的错误代码。有没有一种方法可以链接这些函数的替代版本,然后我可以编程以在返回之前设置适当的 errno 值?

最佳答案

链接器选项 --wrap就是为了这个目的。

一些调用open的代码:-

ma​​in.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/

相关文章:

c++ - 在我的函数中使用简单类时出现 undefined reference 错误

c - 为什么 C 库链接顺序只在某些系统上很重要?

c# - 如何更改基于反射的项目依赖项的 Visual Studio 构建顺序?

c++ - MySQL 连接器/C++ PreparedStatement : forward declaration of ‘class sql::PreparedStatement’

C++变量声明和初始化规则

c++ - 如何处理*.IDL 文件中的循环依赖?

c++ - 使用 QWT 和 Microsoft Visual C++ 2010 绘制 MatLab 等效图

c++ - initializer_list 不可变的性质导致过度复制

windows - VisualC++/vmg/vms 的 G++ 等效项

c++ - 人们会推荐哪些工具来查看 gcc/linux 目标文件?