如何防止其他模块调用我的 c 中的 extern 函数
假设我的程序由多个层组成,例如A 层和B 层。文件a_foo.c包含我的函数定义,文件a_foo.h包含与a_foo.c中的定义相对应的函数声明。
我的设计是同一层中的模块(在本例中为层A)可以调用a_foo.h中声明的函数,而层B则不能调用时包含 a_foo.h 。
那么我怎样才能做到这一点呢?提前致谢 !
suppose my program consists of several layers, say, Layer A and Layer B. The file a_foo.c contains my function definitions, the file a_foo.h contains function declarations corresponding to definitions in a_foo.c.
my design is that modules in the same layer(layer A in this case) can invoke functions declared in a_foo.h while Layer B can not invoke though with a_foo.h included.
so how can i achieve that ? Thanks in advance !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该将两个层分成两个驻留在不同目录中的便利库,并且只有每个层的公共头文件位于公共包含目录中。
因此,您将避免在 B 层中意外包含 a_foo.h。
如果您需要更强的访问控制,则需要依赖于系统的黑客技术。然而,这在大多数情况下是非常不必要的。
You should separate your two layers into two convenience libraries residing in different directories, with only the public header files of each layer in a common include directory.
Thereby, you'll avoid accidental inclusion of a_foo.h in layer B.
If you need stronger access control, you'll need system-dependent hackery. However, this is very unnecessary in most contexts.
想必您在任何给定层中都会有一些(最好仅几个)可以/将与其他层通信的函数。其他大多数仅在该层内部使用。
C 提供的工具是
static
——少数应该对外界可见的函数(可以这么说)是extern
,并在标头。其余的都是静态
。这意味着他们的名字仅在该 TU 内可见,因此其他人无法称呼他们,甚至根本看不到他们。就 a_foo.c 之外的任何内容而言,名称
internal_function1
和internal_function2
根本不存在。它们是完全看不见的。即使我们在 a_foo.h 中包含它们的原型,外部代码仍然无法调用它们或根本无法看到它们。然而,这是 C 提供的唯一工具。就其本身而言,它工作得很好,但是如果 A 层代码足够大,以至于您想要将其分布在多个源文件中,那么事情很快就会变得棘手 - C 只提供两种可见性级别:一个源文件或所有源文件。没有中间级别说它应该在源文件 A、B 和 C 中可见,但在 D、E 或 F 中不可见。
Presumably you'll have a few (preferably only a few) functions in any given layer that can/will communicate with other layers. Most of the others are used only inside of that layer.
The tool C provides to do that is
static
-- the few functions that are supposed to be visible to the outside world (so to speak) areextern
, and prototyped in the header. The rest arestatic
. That means their names are only visible within that TU, so nobody else can call them or even see them at all.As far as anything outside a_foo.c cares, the names
internal_function1
andinternal_function2
don't exist at all. They're completely invisible. Even if we included prototypes for them in a_foo.h, outside code still wouldn't be able to call them or see them at all.This, however, is about the only tool that C provides. For what it is, it works pretty well, but if the A layer code is large enough that you want to distribute it across a number of source files, things get sticky in a hurry -- C only provides two levels of visibility: either one source file, or all source files. There's no intermediate level of saying it should be visible in source files A, B, and C, but not D, E, or F.