Are global variables extern by default or is it equivalent to declaring variable with extern in global?

谁说胖子不能爱 提交于 2019-11-28 10:00:38

is global variables are extern by default in linkage (or) it is equivalent to declaring variable by specifying extern storage class?

The default storage duration, scope and linkage of variables declared outside any block, at the outer most level, have static storage duration, file scope and external linkage. C11 standard says that:

6.2.1 Scopes of identifiers (p4):

[...] If the declarator or type specifier that declares the identifier appears outside of any block or list of parameters, the identifier has file scope, which terminates at the end of the translation unit. [...]

6.2.2 Linkages of identifiers (p5):

[...] If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

6.2.4 Storage durations of objects (p3):

An object whose identifier is declared without the storage-class specifier _Thread_local, and either with external or internal linkage or with the storage-class specifier static, has static storage duration.

So, if x is global

int x;

then its storage duration, scope and linkage is equivalent to x in

extern int x;   

is global variables are static by default in scope (or) it is equivalent to declaring variable by specifying static storage class?

No. As I stated above that its duration is static and it has file scope.

If there is any c or c++ difference please clarify?

No difference. Rule is same in both languages.

is global variables are extern by default in linkage (or) it is equivalent to declaring variable by specifying extern storage class?

Unless otherwise specified, they have external linkage (except in C++, where they have internal linkage if they're constant).

The first answer you link to is saying that it's not equivalent to declaring it extern (which makes it a pure declaration, not a definition); not that it doesn't have external linkage.

is global variables are static by default in scope (or) it is equivalent to declaring variable by specifying static storage class?

In C++, they have internal linkage (as if declared static) if they are constant, external linkage otherwise. In C, they always have external linkage.

If there is any c or c++ difference please clarify?

As mentioned above, the default is always external linkage in C, while in C++ it's internal for constant variables.

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