2016-07-14 65 views
0

我用C創建了一個程序,可以找到一個矩陣隱藏函數和全局變量在頭文件

void fun1(); /*regardless of parameters they take*/ 
void fun2(); 
void fun3(); 
void fun4(); 
void fun5(); 

int global_var1; /*they are used among the above functions*/ 
int global_var2; 
int global_var3; 
int determinant; 

int main(void){ 

int x,y; 

for(x=0; x<something ; x++){ 
    for (y=0 ; y<another_thing; y++){ 
     fun1(); 
     fun2(); 
     fun3(); 
    } 
fun4(); 
fun5(); 
} 

printf("Determinant is: %d\n", determinant); 

return 0; 
} 

void fun1(){/*code goes here to process the matrix*/;} 
void fun2(){/*code goes here to process the matrix*/;} 
void fun3(){/*code goes here to process the matrix*/;} 
void fun4(){/*code goes here to process the matrix*/;} 
void fun5(){/*code goes here to process the matrix*/;} 

的決定現在我需要用這個程序來找到一個給定矩陣的另一個決定因素項目。 我創建了一個頭文件,名爲"matrix.h",我用int find_determinant()替換了int main(void)以用於新項目。

原型的第二方案:

#include "matrix.h" 

int main(void){ 
find_determinant(); /*regardless of para it takes, it works perfectly*/ 
return 0;} 

它工作正常,沒有錯,但是,如果我想給這個頭文件"matrix.h的人在他的程序中使用的唯一問題,他可以知道其他功能的簽名(對他無用,令人困惑),這些功能用於幫助找到int find_determinant()中的行列式。

我的問題是: 如何隱藏(使他們無法訪問)的函數和全局變量,並在第二個C文件/程序包含#include "matrix.h"只顯示int find_determinant()功能?

+2

1.不要將僅在內部使用的東西放在標題中。 2.不需要用戶訪問的全局變量和函數(僅在內部使用)應標記爲「靜態」。 3. * do *需要被外部訪問的全局變量應該在頭文件中用'extern'聲明,並在'.c'文件中定義。 4.你不應該使用如此多的全局變量,並且應該讓函數通過函數參數和返回值來傳遞他們需要的數據。 – Dmitri

+1

一個[類似的問題在這裏](http://stackoverflow.com/questions/15434971/how-to-hide-a-global-variable-which-is-visible-across-multiple-files),但我相信我有看得更相關。提供訪問你想隱藏的功能。 –

回答

1

雖然可以將可執行代碼放在頭文件中,但最好的做法是讓頭文件僅包含聲明(用於全局變量)定義和函數原型。如果你不想給你的源代碼實現,那麼你需要將你的函數編譯成目標代碼,並提供目標文件(作爲靜態存檔或共享庫)以及頭文件。誰想要使用你的功能,然後將他/她的程序鏈接到你的objecet文件/共享庫。這樣,您可以保持自己的源代碼實施。你的頭文件是:

#ifndef __SOME_MACRO_TO_PREVENT_MULTIPLE_INCLUSION__ 
#define __SOME_MACRO_TO_PREVENT_MULTIPLE_INCLUSION__ 

    int find_determinant(); 


#endif 

謹防多次包含的問題(我在上面如何避免這個問題,因此如果您的matrix.h文件包含了好幾次,程序仍然會編譯出)。