在不同环境下正确使用C虚拟函数替换
proper usage of C dummy functions replacement in different environment
我正在尝试在Windows和Linux机器上的套件中添加测试功能。在 linux 机器上,我希望添加真正的函数,而在 Windows 机器上,我希望添加虚拟的 UnsupportedFunction,以便我可以在两个环境中拥有相同数量的函数。
我有以下代码
void UnsupportedFunction(struct1* test)
{
//dummy function in C
}
// following functions defined else where and gets added only if its linux box
#if ENV_LINUX
extern void linuxOnlyFunc1(struct1* test);
extern void linuxOnlyFunc2(struct1* test);
extern void linuxOnlyFunc3(struct1* test);
extern void linuxOnlyFunc4(struct1* test);
#endif
static struct1* addTest(params, TestFunction fnPtr) {
...
}
static void addTestToSuite (struct1* suite,
input devices,
TestFunction testFunction,
const char* testName,
const char* testDescription)
{
TestFunction fnPtr = UnsupportedFunction;
#if ENV_LINUX
fnPtr = linuxOnlyFunc1;
#endif
LinWB_Util_AddTest(params, fnPtr);
}
问题是由于我有很多测试要添加到套件中,所以我必须在所有条目上制作一个丑陋的 if 定义。为了摆脱这些,我必须使用函数调用进行抽象,但是,这些外部函数在 Windows env 上不存在,我最终会收到编译器错误或警告(被认为是错误)。如何以更好的方式设计它?
像这样的东西怎么样
#if ENV_LINUX
extern void linuxOnlyFunc1(struct1* test);
extern void linuxOnlyFunc2(struct1* test);
extern void linuxOnlyFunc3(struct1* test);
extern void linuxOnlyFunc4(struct1* test);
#else
#define linuxOnlyFunc1 UnsupportedFunction
#define linuxOnlyFunc2 UnsupportedFunction
...
#endif
我还没有测试过这个,所以它可能需要一些调整,但你可以做这样的事情:
#if ENV_LINUX
#define linux_only(x) extern void x(struct1* test);
#else
#define linux_only(x) inline void x(struct1* test) { UnsupportedFunction(test); }
#endif
linux_only(linuxOnlyFunc1);
linux_only(linuxOnlyFunc2);
linux_only(linuxOnlyFunc3);
linux_only(linuxOnlyFunc4);
可以使用包含文件来存储函数声明。因此,您不必将它们写入每个源文件。如果函数被证明是未定义的,只需编写这样的函数。
根据要求,我详细说明。
你创建一个名为"fakefuns.h"的文件,其中包含你的函数声明:
#if ENV_LINUX
extern void linuxOnlyFunc1(struct1* test);
extern void linuxOnlyFunc2(struct1* test);
extern void linuxOnlyFunc3(struct1* test);
extern void linuxOnlyFunc4(struct1* test);
#endif
然后,您可以通过添加
#include "fakefuns.h"
到源文件中,最好靠近第一行。在一个源文件中,您实际上实现了这些功能,适用于 Linux 和 Windows。如果他们不应该在Windows中进行任何工作,则实现将非常简单。
相关文章:
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 类型擦除的std::function与虚拟函数调用的开销
- 重写虚拟函数和继承
- 用纯虚拟函数兜圈子
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 禁止子函数调用父级的抽象(或虚拟)函数
- 无法在子类中使用虚拟函数C++
- 无法在派生对象上运行虚拟函数
- 我可以调用从 main() 覆盖的虚拟函数吗?
- 在 C++ 中将函数获取和设置为虚拟函数
- 使用在堆栈上创建的对象调用虚拟函数
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在C++中使虚拟函数私有化
- 模板继承类中的虚拟函数
- 为什么构造函数的虚拟函数调用有时有效,但其他调用却无效
- doxygenc++虚拟函数和实现
- 如何从派生类函数中调用虚拟函数