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:
extern
by default in linkage (or) is it equivalent to declaring variables by specifying extern
storage class?static
by default in scope (or) is it equivalent to declaring variables by specifying static
storage class?C
or C++
? Can anyone please clarify?In a const variable declaration, it specifies that the variable has external linkage. The extern must be applied to all declarations in all files. (Global const variables have internal linkage by default.)
Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.
The default value of global variable a : 0 The default value of global static variable b : 0 The default value of local variable x : 0 The default value of local static variable y : 0 The value of local variable z : 28.
In C, functions are global by default. The “static” keyword before a function name makes it static.
is global variables are
extern
by default in linkage (or) it is equivalent to declaring variable by specifyingextern
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:
[...] 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. [...]
[...] If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is
external
.
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 specifierstatic
, 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 specifyingstatic
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With