2014-12-31 31 views
1

我想在Windows和Linux機器上的套件中添加測試函數。在Linux機器上,我想要添加真正的功能,並在Windows機器上我想要添加虛擬UnsupportedFunction,以便我可以在這兩種環境中具有相同數量的功能。在不同的環境中正確使用C虛擬函數替換

我有以下代碼

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-定義了所有條目。爲了擺脫這些,我必須抽象一個函數調用,但是,這些externs功能不存在於Windows環境,我最終得到編譯器錯誤或警告(視爲錯誤)。 如何以更好的方式設計這個?

+1

歡迎來到平臺的世界「兼容性」。即使是大型項目,甚至是在應該兼容的平臺上共享的代碼,處理這些事情的最常見方式是使用(可能)大量預處理器條件編譯。 –

回答

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 
0

您可以使用包含文件來存儲您的函數聲明。因此,您不必將它們寫入每個源文件。如果函數變得未定義,只需編寫這些函數即可。

根據要求,我詳細說明。

您創建一個名爲「fakefuns.h」文件,其中包含你的函數聲明:加入

#include "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 

那麼您可以在每個源文件中的這些定義,最好靠近第一條線。在一個源文件中,你實際上實現了Linux和Windows的這些功能。如果他們不應該在Windows中進行任何工作,那麼實現將非常簡單。

+0

你能否詳細說明你的想法? – bicepjai

+0

但UnsupportedFunction如何獲得用於Linux測試,在只有Windows測試運行的Linux機器上? – bicepjai

+0

Windows實現可以調用或者是UnsupportedFunction。這樣,就沒有必要提及它可能在每個源文件中都不受支持的事實。 –

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); 
+0

這似乎是正確的 – bicepjai