What does the extern keyword mean?

谁说胖子不能爱 提交于 2019-11-28 04:28:03

extern gives 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.

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.

You can find a more complete description here.

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.

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

For Example: Notification.h

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

Notification.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.

Without extern keyword For Notification constant will create following error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!