如何通过C中的头文件使函数可见

How to make a function visible through a header file in C

我在库中有几个头文件:header1.hheader2.h... 我还有一个库的通用头文件:mylib.h

我希望用户导入 main.h 文件并访问 其他头文件中的部分函数

例如在图书馆:

// header1.h
void a(void);
void b(void);

-

// mylib.h

// I can't use this:
#include "header1.h"
// because it would make b function visible.

// Link to function a ????????

在我的主程序中:

// main.c
#include "mylib.h"

int main(void) {

    a(); // Visible: no problem
    b(); // Not visible: error

    return 0;
}

将函数原型分成不同的 header,这取决于它们是否应该是 "visible"*1(但应该是 "internal" ).

  • header1_internal.h
  • header1.h
  • header2_internal.h
  • header2.h
  • ...

将相关的 *.h header.

包含到 *_internal.h header 中

*_internal.h header 包含到您的库的相关模块中。

不要将任何 *_internal.h 包含在 mylib.h 中。


*1:请注意,即使不以这种方式提供原型,用户也可能会制作 his/her 自己的原型,然后 link 来自 [=19 的函数=].因此,未原型化的功能并非无法访问。

如果其他头文件不需要void b(void),并且您可以访问源文件,那么将声明移到源文件中怎么样?

// header1.h
void a(void);
//void b(void);

// header1.c
/* some #include here */
void b(void);
/* other code here */
void b(void) {
    /* implement it */
}

头文件只包含头文件用户应该可以访问的函数。它们代表 public 接口。

先看这个: Organizing code into multiple files 1 YouTube link:Organizing code into multiple files 1

Organizing code into multiple files 2 YouTube link:Organizing code into multiple files 2

此外,您可以参考 Introduction To GCC by Brian Gough 以更深入地了解编译和使用 gcc linking 过程。