Table of contents
1.
Introduction
2.
What is the Extern Keyword in C?
2.1.
Syntax of Extern keyword in C
3.
Uses of C Extern Keyword
4.
Example of extern Variable in C
5.
Properties of extern Variable in C
6.
Why is the Extern Keyword in C Important?
7.
Linking and Resolving Extern Symbols in C
8.
What is C Extern Variable?
8.1.
Syntax of C Extern Variable 
9.
Declaring and Using Extern Variables in C
10.
What is C Extern Function?
10.1.
Syntax of C Extern Function
11.
Declaring and Using Extern Functions in C
12.
Errors to Watch Out for When Using Extern Keyword in C
13.
Comparison Table of Extern Keyword and Static Keyword in C
14.
Effective Strategies for Utilising Extern Keyword in C
15.
Frequently Asked Questions
15.1.
How does using the extern keyword affect the accessibility of a variable in a C program?
15.2.
What is the difference between static and extern keyword in C?
15.3.
Is it valid to use the extern keyword in combination with typedefs in the C programming language?
15.4.
Is it possible to declare and define a variable with the extern keyword in C? 
16.
Conclusion
Last Updated: Mar 27, 2024
Easy

Extern Keyword in C

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ninjas, hello! Are you familiar with the extern keyword in C programming language? Even if you are unfamiliar, let me introduce you to a valuable tool to help you manage your code and prevent duplication.

The core concept of the extern keyword in C is frequently used when working with several source files. Writing modular and maintainable code in C requires understanding when and how to utilize the extern keyword. This article will offer helpful insights into this powerful language feature, regardless of your programming skill level in C.

extern keyword in C

We'll explain everything to help you understand the concept better. By the end of this article, you'll understand how and when to use the extern keyword in C programs.

What is the Extern Keyword in C?

Variables and functions defined in another source file or library are marked with the extern keyword in C. It tells the compiler that the variable or function exists somewhere else and that it should not allocate space for it in the current source file. Variables and processes can be shared between source files without duplicating data or code.

Syntax of Extern keyword in C

The syntax of the extern keyword in C is as follows:

extern data_type variable_name or function_name;

Uses of C Extern Keyword

The extern keyword is used when declaring a variable or function in C defined in another file. This enables access to the variable or function from other program files.

The extern keyword in C is used in the following situations:

  • To declare an externally specified global variable.
extern int glo_variable;

 

This declaration informs the compiler that the variable glo_variable is defined in a different file. The glo_variable identifier can then be used to access the variable from any file in the program.
 

  • Defining a function that is found in another file and declared.
extern void ex_function(void);

 

This declaration informs the compiler that the function ex_function is defined in a different file. The ex_function() function call can then be used to invoke the function from any program file.
 

Similarly, the extern keyword can also be used: 

  • To transfer data between several programme units.
     
  • To prevent having duplicate code in different files.
     
  • To enable a feature for use by other programs.

 

Example of extern Variable in C

Here is the syntax of an extern variable “var” in C.

extern int var;

 

Here, the variable var of the integer type has been declared. Remember that var has not yet received a definition or memory allocation. Now, understand it using an example of extern variable in C.

#include <stdio.h>
extern int var;
 int main(void)
 {
  return 0;
 }
You can also try this code with Online C Compiler
Run Code

 

Explanation:

This programme was successfully compiled. Here, only var is declared. 

Properties of extern Variable in C

The properties of the extern variable are as follows:

  • To increase the visibility of variables, use the "extern" keyword.
     
  • While definitions can be made multiple times, declarations can only be made once.
     
  • When memory for an extern variable is allocated at initialization, it is considered to be defined.
     
  • Variables that contain the word extern are only declared, not defined.
     
  • The compiler generates no errors since it takes the contents of that extern variable as true. When the linker discovers that no such variable exists, it throws an error.
     

Also read,  Short int in C Programming and Floyd's Triangle in C

Why is the Extern Keyword in C Important?

You can share data and functions between different source files without duplicating them, making your code more modular. When used during compilation, the extern keyword links additional object files together, ensuring that the program runs correctly, saving memory, and making your code easier to read and modify.

Linking and Resolving Extern Symbols in C

Using the extern keyword to declare a variable or function in C means telling the compiler that the definition is elsewhere in the compiled file. Instead of generating code for that variable or function, the compiler generates a reference.

  • All the object files holding the definitions of the variables or functions must be linked to create a complete program.
     
  • The linker reads every object file during linking and generates a symbol table listing every symbol defined and used by the program.
     
  • The linker then looks for the definitions of any extern variables or functions in your program.
     
  • If they are discovered, the object files' pointers to the variables' or functions' memory addresses are replaced.
     
  • If the definition cannot be located, an error is produced.

What is C Extern Variable?

The extern keyword in C will create an external link for any declared variables or functions. When a variable is declared in another scope of the same file or in a different file, the extern keyword in C makes it a global variable that may be accessed from anywhere in the programme.

Syntax of C Extern Variable 

extern data_type variable_name;

Declaring and Using Extern Variables in C

Here's an example that shows how to declare and use extern variables in C:

Suppose we have two source files, extern-keyword-file-1.c, and extern-keyword-file-2.c.

// extern-keyword-file-1.c

#include <stdio.h>
extern int x;
int main() 
{
   printf("x to the power 2 is %d\n", x*x);
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

// extern-keyword-file-2.c

int x = 10; // define x
You can also try this code with Online C Compiler
Run Code

Output

output 1
  • The integer variable x is defined in extern-keyword-file-2.c, and its value is set to 10.
     
  • We declare the variable x in extern-keyword-file-1.c using the extern keyword defined in another source file. 
     
  • The output of x to the power of 2 is then printed using the value of x.
     
  • Together, we compile extern-keyword-file-1.c and extern-keyword-file-2.c. The extern-keyword-file-1.c reference to x will subsequently be resolved to the extern-keyword-file-2.c definition of x by the linker.
     
  • If the extern keyword were used correctly to transfer the value of x across the two source files, the program would produce "x to the power 2 is 100" when it is run.

What is C Extern Function?

The extern keyword has no effect when applied to a function declaration since the declaration extern int inc(int) is identical to int inc(int). This is so because an implicit extern is used in every function declaration. Or, to put it another way, every function in a library's public header is "extern," however, labelling them as such may not even be useful depending on the compiler.

Syntax of C Extern Function

extern data_type function_name;

Declaring and Using Extern Functions in C

The extern keyword can also be used to declare a function. When used in conjunction with a function, the extern tells the compiler not to try to create the function's code in the current file because it is defined in a different file.

Here's an example:

Suppose we have two source files, extern-keyword-file-1.c, and extern-keyword-file-2.c. The definition of the variable x is present in extern-keyword-file-2.c

// extern-keyword-file-1.c

#include <stdio.h>
extern int powerofx();
extern int x;
int main() 
{
  int answer = powerofx(); 
  printf("x to the power 2 is %d\n", answer);
  return 0;
}
You can also try this code with Online C Compiler
Run Code

 

// extern-keyword-file-2.c

#include<math.h>
int x = 10; // define x
int powerofx()
{
	return x*x;
}
You can also try this code with Online C Compiler
Run Code

Output

output 2
  • In this code, we have two source files, extern-keyword-file-1.c, and extern-keyword-file-2.c. In extern-keyword-file-1.c, we declare an extern variable x and a function powerofx(), defined in extern-keyword-file-2.c. We use the function powerofx() to calculate the value of x to the power of 2, and print it to the console.
     
  • In extern-keyword-file-2.c, we define the variable x and the function powerofx(), which calculates the value of x to the power of 2 using the pow() function from the math.h library.
     
  • When we compile and link both files, the linker will resolve the reference to x in extern-keyword-file-1.c to the definition of x in extern-keyword-file-2.c, and the reference to powerofx() in extern-keyword-file-1.c to the definition of powerofx() in extern-keyword-file-2.c.
     

Extern can also be used in sophisticated situations like shared libraries or dynamic linking, in addition to its application for declaring variables and functions in other source files or libraries.

Errors to Watch Out for When Using Extern Keyword in C

Here are some typical errors and traps to avoid when employing an extern keyword in C:

  • If a variable or function is declared to be an extern, it must be defined in a separate file or library. Without a definition, a problem will be noticed by the linker.
     
  • If you declare a variable or function as an extern in one file and then define it in another, the linker can require clarification; you may need to provide additional information, such as the correct name of the file containing the definition or the correct path to the file and find an error.
     
  • If you link the object files in the wrong order, the linker might not find the correct definitions of extern variables or functions and might report an error.
error message

Comparison Table of Extern Keyword and Static Keyword in C

In C, several methods exist for sharing data and functions between source files, including extern and static. Here's a comparison:

Feature Extern Static
Declaration When a variable or function is declared to be defined in a different source, the word "extern" indicates this. A file, making it accessible to the current source file without requiring more explanation. The static keyword allows space for a variable or function within the same file in which it is defined, enabling it to hold onto its value for the duration of the program.
Scope Global scope File Scope
Lifetime The "extern" keyword specifies a variable or function that can be utilized at any time throughout the program. The "static" keyword allows space for a variable or function that keeps its value during the execution of the program.
Storage

When a variable or function is declared to exist, but no memory is allotted, the program can access it without defining it again using the "extern" keyword.

 

The static keyword reserves memory for a variable or function for the program's execution, ensuring its value is kept and available.
Accessibility When a variable or function is marked as extern, it can be used from anywhere in the program as long as its declaration is included in each source file where it is utilized. The "static" keyword prevents other source files from accessing or altering a variable or function outside of the file in which it is defined.

Must Read Passing Arrays to Function in C

Effective Strategies for Utilising Extern Keyword in C

Let's explore practical strategies for using the extern keyword in C programming. 
 

  1. Employ "extern" only when needed: Using the extern keyword when transferring data or functions between files is preferable. It is preferable to provide the same functionality without using "extern" if possible. This can make our code easier to comprehend, which is highly beneficial for complex programs.
     
  2. Include "extern" declarations in header files: Declaring extern variables and functions in a header file that may be included in different source files will make managing this sharing of data and functions easier. By doing this, the program will be consistent in its use of the same declarations.
     
  3. Prevent circular dependencies between files: Ensuring that each header file only contains the declarations required for that file is one technique to avoid circular dependencies. Also, if a header file is not needed, it should not be in another header file. By doing this, we may decrease the header file dependencies and improve the readability of our code.
     
  4. Use the "static" keyword to localize global variables: Our code's maintainability can be improved by limiting the scope of global variables by using the "static" keyword rather than "extern". This can help us understand how variables are used and changed more efficiently, reducing problems and improving the readability of our code.

Frequently Asked Questions

How does using the extern keyword affect the accessibility of a variable in a C program?

When you declare a variable in C with the extern keyword, it becomes accessible and used in other areas of your program. This makes data sharing across several functions and modules easier because you may utilize the same variable across many source files. The variable would only be usable in the file where it was declared without the extern keyword.

What is the difference between static and extern keyword in C?

Extern allows access to functions defined in other files and ensures that global variables defined in one file are also known in another. A variable is only globally known in this file if it is static.

Is it valid to use the extern keyword in combination with typedefs in the C programming language?

The extern keyword can be used in the C programming language with typedefs. While typedef creates an alias for a data type, the extern keyword defines a variable or function as existing elsewhere. The typedef declaration must come before the extern declaration when an extern variable is declared with a typedef.

Is it possible to declare and define a variable with the extern keyword in C? 

The extern keyword cannot be used to declare and define a variable in C. When a variable or function is declared as existing elsewhere, it is defined in another source file and referenced by the extern keyword. It is not used in the current source file to define variables or functions. To use an extern variable in a C program, you must define it without the extern keyword in a different source file from where you declare it. This allows the compiler to link the two files and resolve the variable reference.

Conclusion

This article has introduced the extern keyword in the C programming language. It would help you to understand what extern keyword is used for and how it can be applied in your code. If you want to learn more about the extern keyword, additional resources are available to explore the topic more deeply. By reviewing these resources, you can expand your knowledge of extern and better understand how it can be used effectively in large-scale software projects.

 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our coursesrefer to the mock test and problems look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Live masterclass