Extern Storage Class in C

SPONSOR AD

Extern Storage Class in C Language with Examples

In this article, I will discuss the Extern Storage Class in C Language with Examples. Please read our previous articles discussing Static Storage Class in C Language with Examples. At the end of this article, you will understand the following pointers:

  1. What is Extern Storage Class in C?
  2. Extern Storage Class Examples in C
  3. When Should We Use Extern Storage Class in C Language?
  4. Advantages of Extern Storage Class in C Language.
  5. Disadvantages of Extern Storage Class in C Language.
Extern Storage Class in C Language

In C programming, the extern storage class is used to declare a global variable or function in one file, which can be used in other files. This is particularly useful in multi-file programs. The extern keyword extends the visibility of the C variables and functions.

Here are the key characteristics of the extern storage class:

  • Declaration: This tells the compiler about the existence and type of a variable or a function but does not allocate space for it. With extern, you declare a variable or function in one file and tell the compiler that its definition and memory allocation will be in another file.
  • Definition: Allocates memory for the variable or function. This is where the variable or function is actually created.
  • Scope: Variables and functions declared with extern are available globally. They can be used in any file outside of the one in which they are defined, provided those files declare them with extern.
  • Linkage: The extern keyword provides external linkage. This means that the variables and functions are accessible across different files.
  • Initialization: External variables can be initialized with a value. If not initialized, they are automatically initialized to zero (for basic data types)
  • Usage for Variables: When you declare a variable with an extern, you say its definition is somewhere else, usually in another file. This is useful in multi-file projects, where you might have a global variable defined in one file and want to access it in other files.
  • Usage for Functions: The extern keyword is optional for functions because all function declarations are extern by default. However, using an extern for function declarations can improve readability, clearly defining the function elsewhere.

Extern Storage Class Examples in C

In C programming, the extern storage class is used to declare a global variable or function in another file. The extern keyword extends the visibility of the C variables and functions. Here are some examples to illustrate the use of the extern storage class:

SPONSOR AD
Basic Usage of Extern for Variables Program in C:

To illustrate the basic usage of the extern storage class for variables in C, let’s create a simple program split across two files. We will define a global variable in one file and access it in another file using extern.

File 1: main.c

This is the main file where the program’s execution begins. It will use an external variable declared in another file.

#include <stdio.h>

extern int globalVariable; // Declaration of the external variable

int main() {
    printf("Global Variable: %d\n", globalVariable);
    return 0;
}
File 2: helper.c

This file will define and initialize the global variable.

int globalVariable = 10; // Definition and initialization of the global variable
Explanation
  • In helper.c, we define and initialize the global variable globalVariable.
  • In main.c, we use the extern keyword to declare the same variable. This tells the compiler that globalVariable is defined in another file (helper.c).
  • When the program is compiled and linked, the main function in main.c can access and use globalVariable.
Compiling and Running the Program

To compile and run this program, you need to compile both main.c and helper.c and link them together. If you are using a command-line compiler like GCC, you can do this as follows:

gcc main.c helper.c -o myprogram

./myprogram

This will compile both files into a single executable (myprogram) and run it, allowing main.c to access the globalVariable defined in helper.c.

SPONSOR AD
Extern with Function Declaration Program in C:

To demonstrate the use of the extern storage class with function declarations in a multi-file C program, we need to create at least two files: one for the function definition and another for the function call. Here’s an example:

File 1: math_functions.c

This file will define a function, say, and numbers.

#include <stdio.h>

// Function definition
int addNumbers(int a, int b) {
    return a + b;
}
File 2: main.c

This file will use the addNumbers function defined in math_functions.c.

#include <stdio.h>

// Function declaration with extern
extern int addNumbers(int a, int b);

int main() {
    int sum = addNumbers(5, 3);
    printf("Sum is: %d\n", sum);
    return 0;
}

In this setup:

  • math_functions.c contains the definition of addNumbers.
  • main.c declares the function addNumbers with the extern keyword. This tells the compiler that the function is defined externally, i.e., in another file.

When compiling this program, you need to compile both files and link them together. For example, if you are using GCC, you can compile it like this:

gcc -o myprogram main.c math_functions.c

This will create an executable myprogram that will output “Sum is: 5” when run. The use of extern allows main.c to use the addNumbers function defined in math_functions.c. This is a simple illustration of how an extern can facilitate function declarations across different files in a C program.

Modifying External Variables Program in C:

Creating a program that demonstrates modifying external variables in C involves defining the external variable in one file and then declaring and modifying it in another. This is a common practice in modular programming to share data between different program parts.

SPONSOR AD
File 1: Definition of the External Variable

Let’s start with the first file, say main.c, where we will define and modify the external variable.

main.c:
#include <stdio.h>

// Define the external variable
int extVar;

void modifyExternalVariable();

int main() {
    printf("Initial Value of extVar: %d\n", extVar);

    // Modify the external variable
    modifyExternalVariable();

    printf("Value of extVar after modification: %d\n", extVar);

    return 0;
}
File 2: Declaration and Modification of the External Variable

Next, we’ll have a second file, say modifier.c, where we declare the external variable using the extern keyword and write a function to modify it.

modifier.c:
#include <stdio.h>

// Declare the external variable (defined in another file)
extern int extVar;

// Function to modify the external variable
void modifyExternalVariable() {
    extVar = 100; // Assign a new value
}
Explanation:
  • In main.c, we define the global variable extVar. This variable is accessible in other files as well.
  • In modifier.c, we use the extern keyword to declare extVar as an external variable. This tells the compiler that extVar is not a local variable but defined elsewhere, in this case in main.c.
  • The modifyExternalVariable function is defined in modifier.c, changes the value of extVar.
  • When the program is run, main in main.c will print the initial value of extVar, call modifyExternalVariable to change its value, and then print the new value.
Compiling and Running the Program:

You need to compile both main.c and modifier.c together to create a single executable. If you’re using a command-line compiler like GCC, the command would look something like this:

gcc main.c modifier.c -o myProgram

Then, run the program using:

./myProgram

This example demonstrates how external variables can be shared and modified across different files in a C program, enhancing modularity and allowing for better separation of concerns.

Extern in Multiple Files Program in C:

Creating a program demonstrating the extern keyword across multiple files in C involves dividing the code into separate files. Here’s a simple example with three files: a header file to declare the external variable and two C files for defining and using the variable.

File Structure
  • Common.h – Header file with the external variable declaration.
  • main.c – Contains the main function and uses the external variable.
  • helper.c – Defines the external variable and a function to modify it.
Common.h
// Common.h
#ifndef COMMON_H
#define COMMON_H

extern int sharedVar; // Declaration of the external variable

#endif
main.c
// main.c
#include <stdio.h>
#include "Common.h"

// Function declaration (defined in helper.c)
void modifySharedVar();

int main() {
    printf("Initial Value of sharedVar: %d\n", sharedVar);

    modifySharedVar();

    printf("Value of sharedVar after modification: %d\n", sharedVar);
    return 0;
}
helper.c
// helper.c
#include "Common.h"

int sharedVar = 10; // Definition of the shared variable

void modifySharedVar() {
    sharedVar = 20;
}
Compilation and Execution

To compile and run this program, you would save the code in their respective files and use a C compiler to compile them together. If you’re using a command-line compiler like gcc, the command would look something like this:

gcc main.c helper.c -o myprogram

./myprogram

Program Explanation
  • Common.h contains the declaration of sharedVar with the extern keyword. This header file is included in both C files.
  • In main.c, the sharedVar is used but not defined. It calls modifySharedVar, a function defined in helper.c.
  • In helper.c, the actual definition of sharedVar is provided. The modifySharedVar function modifies this variable.
  • When the program runs, it will display the initial and modified values of sharedVar.

This example illustrates how the extern keyword allows for the shared use of a global variable across multiple files, enhancing modularity and code organization.

Extern with Multiple Declarations Program in C:

Using the extern keyword in C to declare a variable in multiple files is a common technique in multi-file programming. It allows for a variable to be defined in one file and accessed in others. Here’s an example to illustrate this with two C files and a header file.

File Structure:
  • main.c: Contains the main function and uses a global variable declared in another file.
  • helper.c: Defines the global variable.
  • helper.h: Contains the global variable declaration for inclusion in other files.
helper.h:
#ifndef HELPER_H
#define HELPER_H

// Declaration of an extern variable
extern int globalVariable;

#endif
helper.c:
#include "helper.h"

// Definition of the global variable
int globalVariable = 10;
main.c:
#include <stdio.h>
#include "helper.h"  // Includes the extern declaration of globalVariable

int main() {
    printf("Global Variable: %d\n", globalVariable);
    return 0;
}
Explanation:
  • helper.h: This header file declares globalVariable as extern. It’s a common practice to declare global variables in a header file, which can then be included in multiple source files.
  • helper.c: This file includes helper.h and defines globalVariable. The variable is initialized to 10.
  • main.c: This file includes helper.h, which contains the extern declaration of globalVariable. The main function then uses globalVariable.
Compilation and Linking:

To compile and link these files into an executable, you would typically use a command like:

gcc main.c helper.c -o program

Notes:

  • The #ifndef, #define, and #endif preprocessor directives in helper.h are known as “include guards”. They prevent multiple inclusions of the same header file, which can lead to errors or redundant declarations.
  • Having only one definition of the extern variable across all files is important to adhere to the “One Definition Rule” in C. The declaration, however, can (and often does) appear in multiple files.

In these examples, the extern is used to access variables and functions defined in other files, which helps in managing code across multiple files and facilitates modularity in large projects. It’s essential to remember that the extern only declares the variable or function and does not allocate memory. The actual definition (which allocates memory) must be provided in another file.

When should you use the Extern Storage Class in C Language?

The extern storage class in C is used for variables and functions to specify that they have external linkage, meaning they are defined in another file or globally within the same file. This is particularly useful in multi-file programs. Here are some scenarios when you might use the extern storage class:

  • Accessing Global Variables Across Files: When you have global variables defined in one file and need to access them in other files, you can use the extern to declare them in the other files.
  • Modularity and Code Organization: In large programs spread across multiple files, extern allows you to keep the definitions of global variables and functions in one file (like a header file) and use them in various other files. This improves the modularity and organization of the code.
  • Sharing Functions Between Files: Similar to variables, if a function is defined in one file and you need to call it from another, you can use the extern to declare the function’s prototype in the other files.
  • Reducing Namespace Pollution: By declaring variables and functions as extern in header files and defining them in one source file, you can reduce namespace pollution and potential conflicts, as you have clear control over where and how your global identifiers are used.
  • Linkage of Constants: If you have constants that are used across multiple files, you can use extern to share them, ensuring that there is a single source of truth for these values.
Advantages and Disadvantages of Extern Storage Class in C

The extern storage class in C is used to declare a variable or function defined in another file or translation unit. This enables sharing of variables and functions across different files in a program. Here are the advantages and disadvantages of using the extern storage class:

Advantages of Extern Storage Class in C
  • Global Access to Variables and Functions: extern allows variables and functions to be accessed across multiple files, facilitating modular programming and code reusability.
  • Memory Efficiency: Since extern variables are declared in one file and defined in another, it helps manage memory more efficiently by avoiding multiple copies of the same variable.
  • Facilitates Collaboration: Large projects allow different modules or files to share data and functions, making it easier for teams to work on different parts of a program simultaneously.
  • Organized Code: It helps keep the global variables and functions centralized, thus organizing the code better and making it easier to maintain.
  • Flexibility in Code Structure: By using extern, you can define the variables or functions in any file you prefer, offering flexibility in organizing your code structure.
Disadvantages of Extern Storage Class in C
  • Global Dependency: Overuse of extern can lead to tight coupling between different files, making the code less modular and harder to maintain.
  • Risk of Name Collisions: Global variables and functions are shared across all files, which increases the risk of name collisions, especially in large projects.
  • Debugging Difficulty: Debugging issues related to external variables can be more challenging, as the variable’s definition and usage might be in different files.
  • Linkage Errors: If an extern variable is declared but not defined in any file, it will lead to linkage errors at compile time.
  • Potential for Confusing Code: If not used judiciously, the extern can make the program flow hard to follow, as it’s not always immediately clear where a variable is defined or how it’s being modified across different files.

In the next article, I will discuss Pre-Processing in C Language with Examples. In this article, I explain the Extern Storage Class in C Language with Examples. I hope you enjoy this article on Extern Storage Class in C Language with Examples. I would like to have your feedback. Please post your feedback, questions, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *