为什么要使用“extern void my_func();”而不是包含“my_utils.h”?

发布于 2024-09-26 13:38:44 字数 175 浏览 1 评论 0原文

我正在编写一些我没有编写的代码,并注意到有很多 extern void my_func();

我的理解是 extern 用于全局变量,而不是函数。

是否有实际原因将函数声明为 extern 而不是将其放入头文件中并包含该函数?或者这只是一种风格选择?

I'm working on some code I didn't write and noticed that there are many extern void my_func();.

My understanding is that extern in for global variables, not for functions.

Is there a practical reason to declare a function as extern rather than putting it in a header file and including that? Or is this just a stylistic choice?

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

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

发布评论

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

评论(3

撩人痒 2024-10-03 13:38:44

仅当由于某种原因头文件未声明该函数时才需要这样做。并且 extern 对于函数来说始终是不必要的,因为默认情况下函数始终是 extern

This is only needed if, for some reason, the header file doesn't declare the function. And extern is always unnecessary for functions, as functions are always extern by default.

所谓喜欢 2024-10-03 13:38:44

extern 函数的一种用途是假设您有两个模块: module_a (在 module_a.hmodule_a.c 文件中实现)、 module_b (在 module_b.hmodule_b.c 文件中实现)。现在您希望在 module_a 中使用 module_b 的特定函数。但您不想将 module_b 的所有功能公开到 module_a 中。因此,在这种情况下,您可以仅extern所需的函数原型,而不是#include "module_b.h"

One use of extern functions is that suppose you have two modules: module_a (implemented in module_a.h and module_a.c files), module_b (implemented in module_b.h and module_b.c files). Now you want a specific function of module_b to use in module_a. But you don't want to expose all the functionality of module_b into module_a. So that case instead of #include "module_b.h" you can extern the required function prototype only.

呢古 2024-10-03 13:38:44

在使用函数之前在 *.c 文件中声明原型而不是包含整个头文件还不够吗?在任何情况下都不需要对函数使用 extern。我还没有尝试过,但它应该是这样工作的。

Isn't it enough to declare prototype in your *.c file before use of function, instead of including whole header file ? No need to use extern in any case for functions. I have not try yet but it suppose to work that way.

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