C中如何正确使用extern关键字 [英] How to correctly use the extern keyword in C

查看:52
本文介绍了C中如何正确使用extern关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于何时应该在 C 中使用 extern 关键字来引用函数.

My question is about when a function should be referenced with the extern keyword in C.

我不知道什么时候应该在实践中使用它.在我编写程序时,我使用的所有函数都可以通过我包含的头文件使用.那么为什么 extern 访问头文件中未公开的内容会有用?

I am failing to see when this should be used in practice. As I am writing a program all of the functions that I use are made available through the header files I have included. So why would it be useful to extern to get access to something that was not exposed in the header file?

我可能在想 extern 是如何工作不正确的,如果是这样,请纠正我.

I could be thinking about how extern works incorrectly, and if so please correct me.

另外.. 你是否应该extern在头文件中没有关键字的默认声明?

Also.. Should you extern something when it is the default declaration without the keyword in a header file?

推荐答案

extern 更改链接.使用关键字,函数/变量被假定在其他地方可用,解析被推迟到链接器.

extern changes the linkage. With the keyword, the function / variable is assumed to be available somewhere else and the resolving is deferred to the linker.

extern 在函数和变量上是有区别的.

There's a difference between extern on functions and on variables.

对于变量,它不实例化变量本身,即不分配任何内存.这需要在其他地方完成.因此,如果您想从其他地方导入变量,这一点很重要.

For variables it doesn't instantiate the variable itself, i.e. doesn't allocate any memory. This needs to be done somewhere else. Thus it's important if you want to import the variable from somewhere else.

对于函数,这只会告诉编译器链接是外部的.由于这是默认设置(您使用关键字 static 来指示未使用外部链接绑定函数),因此您不需要显式使用它.

For functions, this only tells the compiler that linkage is extern. As this is the default (you use the keyword static to indicate that a function is not bound using extern linkage) you don't need to use it explicitly.

这篇关于C中如何正确使用extern关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆