2013-08-30 36 views
0

我在C程序中有一些模塊,用於沒有運行任何OS的微控制器。每個模塊都有自己的類型定義,枚舉和數據結構定義來表示模塊的狀態,我認爲在模塊的相關頭文件中定義它們是很好用的。頭文件與全局變量相互包含

然後,我在global_var.c中定義了一個全局變量來「記住」整個系統的當前狀態。由於在全局變量定義中引用了模塊的數據結構,因此所有模塊頭都包含在global_var.h中。

但是,這些模塊也需要訪問全局變量,因此它們也需要包含global_var.h。

如果我真的想保留全局變量,如何避免頭文件的相互包含?

非常感謝!

global_var.h

#ifndef GLOBAL_VAR_H 
#define GLOBAL_VAR_H 
#include "module.h" 

typedef struct GLOBAL_STRUCTURE { 
    module_structure m;   
} global_structure; 
#endif 

global_var.c

#include "global_var.h" 
global_structure gs; 

module.h中

#ifndef MODULE_H 
#define MODULE_H 
typedef struct MODULE_STRUCTURE { 
    int a; 
} module_structure; 

void module_function(void); 
#endif 

的module.c

#include "global_var.h" 
extern global_structure gs; 

void module_function(void) { 
    gs.m.a=0; 
} 
+1

您顯示的來源應該編譯。請告訴我們實際上失敗了。 – alk

+1

http://stackoverflow.com/questions/1433204/what-are-extern-variables-in-c –

+2

'extern global_structure gs;'應該放在'global_var.h'中。 – starblue

回答

0

我認爲C語言應該共享一個全局定義兩次。但它取決於編譯器(以及鏈接器),以確定您的工具鏈是否確實有我做過的一些事情,有些事情沒有。最安全的途徑是隻聲明變量一次,並在其他地方顯式聲明它爲extern。你經常會看到這樣做過這樣的:

COMMON.H

#ifundef HELLO 
#define HELLO 
#endif 
HELLO unsigned int myglobx; 

one.c

#include "common.h" 

two.c

#include "common.h" 

three.c

#define HELLO extern 
#include "common.h" 
0

試試這個: 在的module.c 的#define XYZ

然後module.h中中

#define MODULETYPE 
    #ifdef XYZ 
    MODULETYPE 

    #else 
    MODULETYPE extern 
    #endif 
    MODULETYPE int var1,var2; 

這樣做對每個模塊,包括你的頭,無論你想。