Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern keyword usage

Tags:

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(); } 
like image 330
anu Avatar asked Jul 28 '11 06:07

anu


People also ask

When should extern be used?

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

Is extern keyword necessary?

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.

Why do we use extern and static keywords?

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 .

Why do we need extern C?

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.


1 Answers

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.

like image 56
Didier Trosset Avatar answered Oct 16 '22 23:10

Didier Trosset