2012-07-31 71 views
0

我正在做C編程任務,但我很困惑如何組織它。我應該如何組織這個C項目

所以,這裏是情況。我有兩個樹實現,並在兩個單獨的頭文件中聲明它們的struct/includes/function prototypes等等。然後我有兩個c源代碼的兩個實現。現在問題來了。對於樹的ADT,我有一個測試c文件(僅用於運行測試的一個主要功能)。由於這兩個實現將使用相同的測試。我怎樣才能避免做同一個main.c文件的兩個副本?當我包含樹實現的頭文件1時,我可以做gcc Tree_implementation1.c main.c。但要執行implementation2,我必須回到主源文件並手動將include包括到樹實現2中,然後我可以使用相同的編譯命令。我該如何解決這個問題,以便只用一個main.c切換兩個實現?

+0

出於好奇,爲什麼你還要標記這個C++? – 2012-07-31 17:14:34

+0

我在我的數據結構類中,我們使用的這本書非常古老。那時候,他們沒有OOP。所以大多數接口都是使用Pascal在函數中實現的。我主要用C實現了這些,但我還包含了一些方便的C++類,如字符串,流和東西。因此,我也用C++標記了它。 :) – zsljulius 2012-08-01 01:28:37

回答

1

使用預處理和恆定的,你可以在命令行設置:

在你的main.c:

#ifdef TREE_IMPL1 
#include "TreeImplementation1.h" 
#else 
#include "TreeImplementation2.h" 
#endif 

// ... 

int main(int argc, char **argv) 
{ 
#ifdef TREE_IMPL1 
    // code for testing TreeImplementation1 
#else 
    // code for testing TreeImplementation2 
#endif 
} 

當您編譯,或者通過在命令行上省略TREE_IMPL1,或者將其設置在您的IDE中:

gcc -DTREE_IMPL1 main.c ... 
+0

這太棒了! gcc中有很多選項需要學習。謝謝你的幫助! – zsljulius 2012-07-31 17:09:54

1

您的實現是否具有相同的名稱?他們不應該。

如果(或何時)它們不具有相同的名稱,則只需在main.c中包含兩個標頭,然後根據某個預處理器指令測試其中一個標頭。

//main.c 
#include "Tree_implementation1.h" 
#include "Tree_implementation2.h" 

int main() 
{ 
#ifdef TEST_FIRST 
    testFirstTree(); //declared in Tree_implementation1.h 
#else 
    testSecondTree(); //declared in Tree_implementation2.h 
#endif 
    return 0; 
} 
+0

我認爲你的想法與上述基本相同。感謝您的幫助。 – zsljulius 2012-07-31 17:10:51

+0

@zsljulius esentially,是的,但我建議你包括這兩個文件。這樣,潛在的命名衝突就會出現。 – 2012-07-31 17:11:44

1

您的問題的另一種解決方案是使用動態接口。 按照這樣的方式工作:

#include "Imp_1.h" 
#include "Imp_2.h" 

typedef void (*TreeFunctionType1)(Tree,param); 
typedef void (*TreeFunctionType2)(Tree); 

typedef struct ITree 
{ 
    TreeFunctionType1 func1; 
    TreeFunctionType2 func2; 
}ITree; 

static ITree _Itree={0}; 

void SetImp(TreeFunctionType1 f1,TreeFunctionType2 f2) 
{ 
    tree.func1 = f1; 
    tree.func2 = f2; 
} 

/*Use only this functions in your Tests code*/ 
//{ 
void Func1(Tree tree,Param param) 
{ 
    (*_Itree.func1)(tree,param); 
} 

void Func2(Tree tree) 
{ 
    (*_Itree.func2)(tree); 
} 
//} 

int main(int argc, char const *argv[]) 
{ 
    SetImp(Imp_1_f1,Imp_1_f2); 
    TestCode(); 
    SetImp(Imp_2_f1,Imp_2_f2); 
    TestCode(); 
    return 0; 
}