Linux设备驱动程序中的静态函数?

发布于 2024-07-09 14:34:20 字数 112 浏览 9 评论 0原文

Linux代码中设备驱动程序中的大多数函数定义都定义为静态是否有原因? 是否有一个原因?

有人告诉我这是为了确定范围并防止名称空间污染,有人可以详细解释为什么在这种情况下使用静态定义吗?

Is there a reason why most function definition in device driver in linux code is defined as static? Is there a reason for this?

I was told this is for scoping and to prevent namespace pollution, could anyone explain it in detail why static definition is used in this context?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

是你 2024-07-16 14:34:20

声明为静态的函数在定义它们的翻译单元之外是不可见的(翻译单元基本上是一个 .c 文件)。 如果一个函数不需要从文件外部调用,那么应该将其设为静态,以免污染全局命名空间。 这使得相同名称之间发生冲突的可能性较小。 导出的符号通常用某种子系统标签来标识,这进一步减少了冲突的范围。

通常,指向这些函数的指针最终会出现在结构中,因此它们实际上是从定义它们的文件外部调用的,而不是通过它们的函数名称调用的。

Functions declared static are not visible outside the translation unit they are defined in (a translation unit is basically a .c file). If a function does not need to be called from outside the file, then it should be made static so as to not pollute the global namespace. This makes conflicts between names that are the same are less likely to happen. Exported symbols are usually indentified with some sort of subsystem tag, which further reduces scope for conflict.

Often, pointers to these functions end up in structs, so they are actually called from outside the file they are defined in, but not by their function name.

冷默言语 2024-07-16 14:34:20

出于同样的原因,您可以在任何代码中使用static。 您应该只“发布”您的 API 调用,任何其他内容都会让您遭受滥用,例如能够从驱动程序外部调用内部函数,这几乎肯定会是灾难性的。

只让外界看到必要的内容是一种很好的编程习惯。 这就是封装的全部内容。

For the same reasons you use static in any code. You should only 'publish' your API calls, anything else opens you up to abuse, such as being able to call internal functions from outside the driver, something that would almost certainly be catastrophic.

It's good programming practice to only make visible to the outside world what's necessary. That's what encapsulation is all about.

胡大本事 2024-07-16 14:34:20

我同意。 这在任何 C 代码中都是常见且明智的做法 - 不仅仅是内核代码! 不要认为这仅适用于低级内容,任何延伸超过一个 .c 文件的 C 代码都应该考虑到这一点。

I concur. This is common and wise practice in any C code - not just kernel code! Don't go thinking this is only appropriate for low level stuff, any C code that stretches past one .c file should have thought given to this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文