gpt4 book ai didi

linux - C++ 确保我们为单元测试调用模拟系统调用

转载 作者:太空宇宙 更新时间:2023-11-04 12:09:34 24 4
gpt4 key购买 nike

当尝试用 C++ 包装系统调用时,例如 lseek,编译后的代码将调用实际的系统调用而不是我的模拟。

这是一个例子:

/* Mock the file operation lseek. */
off_t lseek(int fd, off_t offset, int whence)
{
printf("%s \n", __PRETTY_FUNCTION__);
}

如何让编译器调用我模拟的系统调用而不是 unistd.h 中的系统调用?

我尝试使用 -Wl,--wrap=lseek 标志,但这失败了,因为链接器找不到 __wrap_lseek 符号。

GNU gcc/ld - wrapping a call to symbol with caller and callee defined in the same object file

最佳答案

我使用 g++ -c 选项进行编译,然后使用 nm 实用程序查看生成的符号的名称。

事实证明,模拟的系统调用名称被 C++ 编译器破坏了。因此,链接器将使用正常的系统调用。

解决方案是用 extern "C"包装模拟的系统调用。

下面是关于这个关键词的讨论:

How to correctly use the extern keyword in C

关于linux - C++ 确保我们为单元测试调用模拟系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49440235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com