I have three programs in which I am using extern
keyword. I am not able to understand the result. Below are three examples:
Example 1: I was expecting that below code will give compilation error that multiple declaration of k
. But it works fine?
int k; //works fine extern int k = 10; void main() { cout<<k<<endl; getchar(); }
Example 2: When I am trying to initialize "k" in above example compiler gives error. Why?
int k = 20; //error extern int k = 10; void main() { cout<<k<<endl; getchar(); }
Example 3: In this example I changed the order of definitions mentioned in example 1. When I compile this code I am getting errors. Why?
extern int k = 10; int k; //error void main() { cout<<k<<endl; getchar(); }
The extern must be applied in all files except the one where the variable is defined. 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.)
If the declaration describes a function or appears outside a function and describes an object with external linkage, the keyword extern is optional. If you do not specify a storage class specifier, the function is assumed to have external linkage.
static means a variable will be globally known only in this file. extern means a global variable defined in another file will also be known in this file, and is also used for accessing functions defined in other files. A local variable defined in a function can also be declared as static .
Using extern "C" lets the compiler know that we want to use C naming and calling conventions. This causes the compiler to sort of entering C mode inside our C++ code. This is needed because C++ compilers mangle the names in their symbol table differently than C compilers and hence behave differently than C compilers.
Example 2: You are trying to initialize a global variable twice, with two different values. This is the error.
Example 3: You first declare an extern
variable, and then define a variable with the same name in the same compilation unit. This is not possible.
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