在不同环境中正确使用C伪函数替换

时间:2014-12-31 00:09:03

标签: c++ c linux windows function-pointers

我正在尝试在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-defined。为了摆脱这些我必须使用函数调用进行抽象,但是,那些被驱逐的函数在Windows环境中不存在,并且我最终得到编译器错误或警告(被认为是错误)。 如何以更好的方式设计这个?

3 个答案:

答案 0 :(得分:4)

这样的东西
#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

答案 1 :(得分:2)

我还没有对此进行测试,所以可能需要进行一些调整,但你可以这样做:

#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);

答案 2 :(得分:0)

您可以使用包含文件来存储函数声明。因此,您不必将它们写入每个源文件。如果函数结果未定义,只需编写这样的函数。

根据要求,我详细说明。

您创建一个名为“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中进行任何工作,那么实现将非常简单。