2012-03-02 143 views
0

好的,我有一個名爲main.c的主源文件,名爲test.h的頭文件和另一個名爲handBeraknare.c的類。 我試圖通過將我的一些方法轉移到類handBeraknare.c來讓我的代碼更具可讀性。創建頭文件時出現問題

所以在main.c我有一個結構,看起來像這樣:

typedef struct kort{ 
    int draget; 
    char farg; 
    int nummer; 
    struct kort *next; 
    }kort; ` 

main.c我創建幾個,這些使用kort k=(kort*)malloc(sizeof(kort));,並把它們放到一個數組。什麼即時嘗試達到是發送這個kort陣列到handBeraknare.c功能,但我得到某種奇怪的錯誤"in file included from handBeraknare.c"

我不知道這與現在知道"kort"是什麼(我的結構)的頭文件有關。總之,這裏的一些代碼:

// in test.h 
int beraknaFarg(kort kortHand[]); 



// in handBeraknare.c 
#include <stdio.h> 
#include "test.h" 
int beraknaFarg(kort kortHand[]){ 
char c = kortHand[0].farg; 
    int i; 
    for (i=1;i<5;i++){ 
     if (kortHand[i].farg!=c){ 
           printf("inte färg"); 
           system("pause"); 
      //Spelaren har inte färg. Retunera 0 
      return 0; 
      } 
     } 
     //Spelaren har färg. Retunera 1 
     printf("!!!!färg"); 
           system("pause"); 
     return 1; 
} 


//part of the main class. Calling function test() 
// which calls the method beraknaHand which exists in handBeraknare.c 

#include "test.h" 
... 

int main(int argc, char *argv[]) 
{ 
    test(); 
} 

// the testfunction in my mainclass 
void test(){ 
     char farg[4]={'S','K','R','J'}; 
     int nummer[14]={0,2,3,4,5,6,7,8,9,10,11,12,13,14}; 
     kort kortArray[52]; 
     kort kortHand[5]; 
        kort *k; 
        k=(kort*)malloc(sizeof(kort));    
        k->farg='s'; 
        k->nummer=5; 
        kortHand[0]=*k; 

        k->farg='s'; 
        k->nummer=11; 
        kortHand[1]=*k; 

        k->farg='s'; 
        k->nummer=12; 
        kortHand[2]=*k; 

        k->farg='s'; 
        k->nummer=11; 
        kortHand[3]=*k; 

        k->farg='s'; 
        k->nummer=9; 
        kortHand[4]=*k; 
    beraknaFarg(kortHand); 
+0

您提供的信息不足夠。 handBeraknare.h是什麼樣的?你能提供確切的錯誤信息嗎? – 2012-03-02 09:07:02

回答

2

製作test.h從main.c中

+0

得到它的工作。這只是語法錯誤的問題。我在頭文件中聲明瞭typedef,並從main.c中完全刪除它。謝謝! – 2012-03-02 09:22:22

1

閱讀

typedef struct kort{ 
     int draget; 
     char farg; 
     int nummer; 
     struct kort *next; 
     } kort; 
int beraknaFarg(kort kortHand[]); 

並取出typedef您需要定義在頭文件中typedef的,然後將頭文件包含在您希望使用它的C文件中。另外,因爲它是typedef的定義而不是聲明,所以你需要在C文件中定義它。 即
.h文件:

typedef strcut 
{ 
    int a; 
    .... 
}t_struct_type; 

C文件:

t_struct_type struct_var; 

如果你想在一個以上的C文件使用struct_var,你需要添加extern關鍵字在H文件。像這樣:extern t_strcut_type struct_var

+0

你的答案有點困惑。但爲工作解決方案+1。我從main類中刪除了整個typedef聲明,而是在我的頭文件中聲明它。我可以使用main和handberaknare中的struct來添加im,而不使用extern關鍵字:) – 2012-03-02 09:23:34