在不同环境下正确使用C虚拟函数替换

proper usage of C dummy functions replacement in different environment

本文关键字:虚拟 函数 替换 环境      更新时间:2023-10-16

我正在尝试在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中进行任何工作,则实现将非常简单。