gpt4 book ai didi

c++ - 在已在共享库中实现的可执行文件中实现静态方法是否安全?

转载 作者:搜寻专家 更新时间:2023-10-31 01:13:35 24 4
gpt4 key购买 nike

我们在代码中使用了很多共享库。在这种特殊情况下,静态方法是在这些库之一中实现的。我们在代码的不同地方调用这个方法。但是,如果我们想测试,我们想隔离进程,所以模拟那个方法的实现。

我们正在考虑的方法是在测试二进制文件中重新实现该方法。这将确保采用我们的实现而不是库中的实现。

这里的主要问题是:这是纯粹的邪恶吗?如果是这样,这种情况的首选解决方案是什么?

一个例子...

共享库的头部:

static const bool theMethod(...);

共享库中方法的实现:

static const bool theMethod(...){
//The real implemetation does some fancy stuff here
return theRealValue;
}

我们的测试用例:

#include <headerOfTheMethod.hpp>

//Our own "mocked" implementation
static const bool theMethod(...){
return true; //Lets say we always return true for the purpose of our test
}

//Here comes our code testing the class which is using that particular method

旁注:我们使用 gcc 作为编译器,库是动态链接的。

更新:如果这适用于静态方法。这将是一个很好的开始,但如果它是类的成员函数会发生什么?

最佳答案

你会违反 One Definition Rule .链接器的工作方式可能对您有用,但这是一场赌博,没有任何保证。

关于c++ - 在已在共享库中实现的可执行文件中实现静态方法是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12354742/

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