【问题标题】:Hide functions and global variables in the header file在头文件中隐藏函数和全局变量
【发布时间】:2016-07-14 20:23:24
【问题描述】:

我用 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 main(void) 替换为int find_determinant(),以便在新项目中使用。

第二个程序的原型:

#include "matrix.h"

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

它工作正常,没什么问题,但唯一的问题是如果我想把这个头文件"matrix.h给某人在他的程序中使用它,他可以知道其他函数的签名(对他一个人没用并且令人困惑)用于帮助找到 int find_determinant() 中的行列式。

我的问题是: 如何隐藏(使它们无法访问)这些函数和全局变量,并在包含 #include "matrix.h" 的第二个 C 文件/程序中仅显示 int find_determinant() 函数?

【问题讨论】:

  • 1.不要将仅在内部使用的内容放在标题中。 2. 不需要用户访问的全局变量和函数(仅供内部使用)应标记为static。 3. do 需要被外部访问的全局变量应该在头文件中用extern 声明,并在.c 文件中定义。 4. 你不应该使用这么多的全局变量,应该让函数通过函数参数和返回值传递它们需要的数据。
  • A similar question here 但我确信我看到了更多相关信息。提供函数来访问您想要隐藏的内容。

标签: c header


【解决方案1】:

虽然您可以将可执行代码放在头文件中,但一个好的做法是让您的头文件仅包含声明(用于全局变量)定义和函数原型。如果您不想提供源代码实现,则需要将函数编译为目标代码并提供目标文件(作为静态存档或共享库)以及头文件。任何想要使用您的功能的人都会将他/她的程序链接到您的对象文件/共享库。这样,您可以将源代码实现留给自己。您的头文件将是:

#ifndef __SOME_MACRO_TO_PREVENT_MULTIPLE_INCLUSION__
#define __SOME_MACRO_TO_PREVENT_MULTIPLE_INCLUSION__

    int find_determinant();


#endif

注意多重包含问题(我已经在上面展示了如何避免这种情况,这样如果您的 matrix.h 文件被多次包含,程序仍然可以编译)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2013-03-04
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多