2012-04-26 84 views
0

文件:element.h展開如何以及在哪裏調用外部定義的結構

#ifndef ELEMENT_H 
#define ELEMENT_H 

typedef struct Elem { 
    char * itag; 
    char * cont; 
    char * etag; 
    struct Elem * previous; 
} Element; 

void printElement (Element *); 
#endif /* ELEMENT_H */ 

我聲明和element.h展開和element.c定義的結構Element(未示出,但在其中執行的malloc)。

文件parser.c的功能之一應該訪問Element。 如果適用某些條件,則會創建一個指向Element的新指針,其中一個指針屬性已填滿。 之後的一些迭代,如果適用其他條件,另一個指針屬性將獲得一些文本。 然後,當滿足其他條件時,應該將指向Element的指針傳遞給另一個文件的函數:output.c

我的問題是:如何以及應該在哪裏撥打Element。 如果在if條件內創建指向它的指針,那麼它就是一個自動變量。迭代函數時不可見。

我可以聲明它static,但編譯器返回一個錯誤error: 'e' undeclared (first use in this function)。例如:在迭代1中,指針在if語句的一個分支中創建;在迭代2,if另一分支訪問,我這樣做​​

如果我宣佈extern Element * e;,得到同樣的錯誤中的if(第一else if)第二分支。

文件output.c

#include element.h 
write_element (Element * e) 
{ 
    write_to_disk(... e->itag, e->etag); 
} 

文件parser.c

#include "element.h" 

# some other functions 
void parser (char * f, char * b) 
{ 
    if (something) { 
     /* Need to access externally defined Element type structure, but it should be visible in all `parser` function */ 
     Element * e; 
     e->itag = ... realloc(...) 
     ... 

    } else if (.....) { 
     /* Should assume a pointer to Element is already created */ 
     e->etag = "a"; 

    } else if (....) { 
     /* Should assume a pointer to Element is already created */ 
     /* and itag, etag and cont have some text */ 
     write_element(e); 
    } 

回答

1

代碼

typedef struct Elem { 
    char * itag; 
    char * cont; 
    char * etag; 
    struct Elem * previous; 
} Element; 

沒有定義的元素。它只是告訴編譯器它的結構。沒有定義一個元素。

具有

extern Element myElement; 

在頭文件嘗試。

在相應.c文件把

Element myElement;

這將預留空間myElement

+0

的主要問題是如何可以初始化元素,宣告外部一個'if'分支內,並將它在包含該函數的其他迭代可訪問此'if'分支,它這'if'分支或'否則如果'分支。 – Luis 2012-04-26 13:59:17

+0

'元素'是數據類型。 'myElement'是包含數據的變量。因此,要設置'itag',例如在代碼中執行'myElement.itag = ...'。 – 2012-04-26 14:03:36

1

你應該使用關鍵字«EXTERN»。例如:

f.h:

#ifndef H_LP_F_20120426154230 
#define H_LP_F_20120426154230 

typedef struct Elem { 
    char *itag; 
    char *cont; 
    char *etag; 
    struct Elem *previous; 
} Element; 

extern Element myStruct; 

#endif 

F。Ç

#include "f.h" 

Element myStruct; 
/* nom I can use myStruct */ 
相關問題