2013-02-04 25 views
0

我正在寫C代碼,它具有以下基本結構:如何在c中對通用數據成員/變量進行分組?

A部分:主模塊的啓動/初始化,調用各種子模塊以及最終完成子模塊結果的合成。

B部分:子模塊的實際執行。

Now, part A has its own main.c and main.h file 
Part B has three modules: 
sub1.c/sub1.h 
sub2.c/sub2.h 
sub3.c/sub3.h 

在子模塊中使用了很多通用變量和函數。 我想有一個通用模塊,可以包含在所有的子模塊中,並且可以使用所有常用的功能/變量。 (common.c和common.h)

現在,對於通用函數,我可以在common.h中聲明它們,然後在common.c中定義,然後它們可以直接在所有子模塊中使用。 但是還有很多常見的數據變量/成員也是我想'普通'出來的。

這樣做最有效的方法是什麼,這樣我可以直接在所有的子模塊中使用它們?

在C++中,它可以添加到common.h中,然後可以與包含common.h的任何文件一起使用,但我相信它在c中有點不同。 有人可以幫忙解釋一下這個區別嗎?

感謝

+2

如果你有很多變量在多個模塊之間共享,那麼你可能有一個設計問題。找到避免共享變量的方法。 –

回答

0

在C或C++:

應該在一個.h

// declaration, means it's defined somewhere else 
// can declare it as many times as you want 
extern int yourVariable; 

每個對象(如在編譯過程中生成的中間文件爲.c.cpp文件,而不是OOP中的對象)想要使用變量需要知道它(因此有一個定義的地方)。

應該去在.c/.cpp

int yourVariable = 3; // definition, should only define it once 
int yourVariable2; // also a definition 

extern關鍵字是可選的功能。

int square(int num); // function declaration (.h) 
extern int square(int num); // same as above 
int square(int num) { return num*num; } // function definition (.c) 

在C++:

應該在一個.h

// this is a declaration 
class yourClass 
{ 
    int yourVariable; 
} 

應該在一個.cpp

int yourClass::yourVariable = 3; 

我可能是錯的,但我m不知道C和C++之間的區別在這方面(除了C++有類)。

+0

謝謝。一個附加問題。我想要在所有模塊中具有相同的變量值。例如:errrocode,如果其中一個模塊將其更改爲-12,則其他人也應該能夠將其視爲-12。這怎麼可能? – Sunny

+0

只需在'.c' /'.cpp'文件中使用'extern int errorCode;'在一個常見的'.h'和'int errorCode;'中。 – Dukeling

相關問題