2016-07-14 26 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文件包含了好几次,程序仍然会编译出)。