Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

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

I have gone through following two questions:

static and extern global variables in C and C++

global variable in C are static or not?

Both questions says the two things in different way.

Question 1's Answer:

Global variables are not extern nor static by default on C and C++.

Question 2's Answer:

If you do not specify a storage class (that is, the extern or static keywords), then by default global variables have external linkage

I need to know the following:

  1. Are global variables extern by default in linkage (or) is it equivalent to declaring variables by specifying extern storage class?
  2. Are global variables static by default in scope (or) is it equivalent to declaring variables by specifying static storage class?
  3. Is there any difference with C or C++? Can anyone please clarify?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...