2014-09-19 102 views
1

頭文件中的聲明的意義:向前聲明錯誤,我有麻煩

typedef struct Queue *QueueP; 

C語言文件執行:

struct Queue 
    { 
     char *head; 
     char *tail; 
     QueueItemT item; //char typedef from the header file, not what's giving error 
     int SizeL; 
     int sizeP; 
     int QueueSize; 
    }; 

C主程序文件:

#include <stdio.h> 
    #include <stdlib.h> 
    #include "Queue1.h" 

    int main() 
    { 
     struct Queue queue; 
     QueueP myQueue = &queue; 
     return 0; 
    } 

我得到以下行中的錯誤分別爲以下消息:

struct Queue queue; 
       ^
       Main : variable has incomplete type 'struct Queue' 

    typedef struct Queue *QueueP; 
       ^
        Header : note: forward declaration of 'struct Queue' 

任何想法可能會導致這些錯誤?我對C中的多個文件和頭文件的工作很陌生,所以我真的無法解決這些錯誤。任何幫助將是偉大的,謝謝!

回答

0

將結構定義放入c文件中。這不是它的工作原理:您需要將定義放入標題中。

這是因爲struct的定義是而不是的一個實現。 C編譯器需要這些信息才能正確處理struct的聲明。前向聲明可以讓你定義一個指向你的struct;聲明一個struct本身需要一個完整的定義。

如果你想保持你的私人struct的細節,把它變成一個私有的頭文件。包括從您的私人頭公頭文件,也:

queue.h

typedef struct Queue *QueueP; 

queue_def.h

#include "queue.h" 
struct Queue 
{ 
    char *head; 
    char *tail; 
    QueueItemT item; //char typedef from the header file, not what's giving error 
    int SizeL; 
    int sizeP; 
    int QueueSize; 
}; 

的main.c:

#include <stdio.h> 
#include <stdlib.h> 
#include "queue_def.h" 

現在項目應該編譯沒有問題。

+0

這就是它,清除了錯誤,它幫助我理解了它。非常感謝! – like9orphanz 2014-09-19 03:11:20

0

事實上,我正向前聲明問題的原因是因爲我試圖從主文件中存取結構(這是在.c文件中聲明)。

這不僅是不好的編程習慣,該項目的期望功能是最終用戶(即使用接口和實現來構建他們的'main.c'文件的人)應該不知道什麼樣的結構正在被使用時,他們應該簡單地能夠建立一個具有所給功能的隊列,而不知道幕後發生了什麼。

D'oh !!!