extern Keyword in C Programming

The extern keyword in C language lets us use global variables and functions from other files. 

Consider the code below,





The variables n1, f1 and c1 were defined in a file called devil.c,


The output of extern2.c is, 


Now consider the below code,



The output of this code is,


Another example of extern keyword:

The first time we declare globalVar with extern keyword.

The second time we do not use extern keyword.


Then we give globalVar a value in file1.


Our main function is in file2.

When we execute file2 in both cases(using extern and not using extern) we get the same output.



So why do we use the extern keyword?

While it might seem that you can use global variables from a header file without explicitly using extern, there are cases where using extern is necessary and beneficial for code organisation and to avoid potential issues.

First of all we use it to avoid multiple definitions. If you include a header file containing a global variable in multiple source files, each source file would have its own copy of the variable. This can lead to linker errors due to multiple definitions of the same symbol. By using extern in the header and defining the variable in only one source file, you ensure that there's a single definition for the variable.

Using extern also improves code readability. Using extern explicitly indicates that the variable is defined elsewhere and is not a local variable. This helps other developers understand that the variable is a global resource shared among different source files.

This also helps hide the implementation details of functions and variables in the source files. This is a fundamental principle of encapsulation and abstraction, enabling you to change the implementation without affecting other parts of the code that depend on the variable.

The text editor I have used is Sublime Text.
Download Link: https://www.sublimetext.com/download

Happy Independence Day!

Comments