C语言 extern 关键字是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2753962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:20:40  来源:igfitidea点击:

What does the extern keyword mean?

cobjective-cextern

提问by dontWatchMyProfile

What does the externkeyword mean? I've seen that in front of an function declaration like

什么是extern关键字是什么意思?我已经在函数声明前看到过,例如

extern void DoFoo ...

采纳答案by CB Bailey

externgives a name external linkage. This means that the object or function is accessible through this name from other translation units in the program. For functions, this is the default linkage in any case so its usage (in this context) is usually redundant.

extern给出一个名称外部链接。这意味着可以从程序中的其他翻译单元通过这个名称访问对象或函数。对于函数,这在任何情况下都是默认链接,因此它的使用(在此上下文中)通常是多余的。

回答by Romain Hippeau

The extern keyword declares a variable or function and specifies that it has external linkage (its name is visible from files other than the one in which it's defined). When modifying a variable, extern specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends). The variable or function may be defined in another source file, or later in the same file. Declarations of variables and functions at file scope are external by default.

extern 关键字声明一个变量或函数,并指定它具有外部链接(它的名称在定义它的文件之外的文件中可见)。修改变量时,extern 指定变量具有静态持续时间(在程序开始时分配,在程序结束时释放)。变量或函数可能在另一个源文件中定义,或稍后在同一文件中定义。默认情况下,文件范围内的变量和函数声明是外部的。

You can find a more complete description here.

您可以在此处找到更完整的说明

回答by Sujananth

For Beginners,

对新手而言,

Initially I was confused to learn that, "the extern keyword declares a variable or function and specifies that it has external linkage" by @Romain Hippeau.

最初我很困惑,@Romain Hippeau了解到“ extern 关键字声明了一个变量或函数并指定它具有外部链接”。

Now I understood that, we will be able to share our variables with other classes through extern keyword.

现在我明白了,我们将能够通过 extern 关键字与其他类共享我们的变量。

For Example: Notification.h

例如:Notification.h

 #import <Foundation/Foundation.h>
 extern const NSString* notificationConstant;

Notification.m

通知.m

 #import "Notification.h"
 const NSString* notificationConstant = @"NotificationConstant";

By importing notification.h in any of my other classes, I can read the value of string NotificationConstant.

通过在我的任何其他类中导入 notification.h,我可以读取字符串 NotificationConstant 的值。

Without extern keyword For Notification constant will create following error. enter image description here

没有 extern 关键字 For Notification 常量会产生以下错误。 在此处输入图片说明