Storage Class #4: extern
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Showcase extern Storage Class Across Multiple Source Files

📑 On this page:
  • What Does extern Mean?
  • Simple Rules to Remember
  • Complete Example (3 Files)
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What extern means, in plain words
  • How one global variable can be shared across two or more source files
  • How the compiler and linker work together to make that happen
  • The difference between a declaration (extern) and a definition (without extern)
  • Why you see "undefined reference" errors — and how to fix them

What Does extern Mean?

When you split a C program into multiple files, each file is compiled separately. That means a variable defined in one file is invisible to another file by default.

The extern keyword fixes that. It says to the compiler: "This variable exists somewhere else — trust me, I'll link it up later." You use extern in the file that uses the variable. You do not use extern in the file where the variable is created.

💡 In one line: extern means "declared here, defined elsewhere". One file creates the variable; other files say extern to use it.

C program showcasing the extern storage class sharing a global variable across multiple source files

Simple Rules to Remember

Question Answer
Where do I put extern?In files that use the variable, not where it's defined
How many definitions?Exactly one across the whole program
How many declarations?As many as you want — one per file that needs it
Default value?Zero (for the one real definition)
When is it created?Before main runs; destroyed when the program ends
What if I forget the definition?Linker error: "undefined reference"

Complete Example (3 Files)

We'll split a small program into three files: one defines the global variable, one uses it, and one has main.

File 1: globals.c — the one and only definition

/* globals.c - the ONE place where sharedCounter is created */
int sharedCounter = 0;
                                    

This is the actual definition. No extern keyword — that's important. It allocates storage for the variable and initializes it to 0.

File 2: helpers.c — uses the variable via extern

/* helpers.c - uses the shared variable from globals.c */
#include <stdio.h>

extern int sharedCounter;   /* declared here, defined in globals.c */

void incrementCounter(void) {
    sharedCounter++;
    printf("helpers.c  -> after increment: %d\n", sharedCounter);
}

void showCounter(void) {
    printf("helpers.c  -> current value  : %d\n", sharedCounter);
}
                                    

The extern line is a declaration. It tells the compiler: "trust me, a variable called sharedCounter exists somewhere in the program." The compiler accepts it and moves on — the linker will connect it later.

File 3: main.c — also uses the variable

/* main.c - entry point, also reads the shared variable */
#include <stdio.h>

extern int sharedCounter;   /* same declaration here */

void incrementCounter(void);    /* defined in helpers.c */
void showCounter(void);         /* defined in helpers.c */

int main(void) {
    printf("main.c     -> start value    : %d\n", sharedCounter);

    sharedCounter = 10;
    printf("main.c     -> set to         : %d\n", sharedCounter);

    incrementCounter();       /* helpers.c increments the same variable */
    incrementCounter();
    showCounter();

    printf("main.c     -> final value    : %d\n", sharedCounter);

    return 0;
}
                                    

Compile and run

gcc main.c helpers.c globals.c -o demo
./demo
                                    

Program Output

main.c     -> start value    : 0
main.c     -> set to         : 10
helpers.c  -> after increment: 11
helpers.c  -> after increment: 12
helpers.c  -> current value  : 12
main.c     -> final value    : 12
                                

Step-by-Step Explanation

Let's look at what happens step by step.

1. Before main runs:

The program starts. The linker has already stitched the three object files together. sharedCounter sits in the program's data area, initialized to 0 by the single definition in globals.c.

2. main reads the variable:

printf("main.c     -> start value    : %d\n", sharedCounter);
                                

Prints 0. The extern declaration in main.c lets the compiler generate code that reads from that memory location.

3. main writes to the variable:

sharedCounter = 10;
                                

Any function in any file that sees the same extern declaration can read and write the same memory location. Setting it to 10 affects everyone.

4. helpers.c increments it:

sharedCounter++;
                                

This runs inside helpers.c, but it's modifying the same variable defined in globals.c. After two calls, it becomes 12.

5. Back in main, the variable still shows 12:

printf("main.c     -> final value    : %d\n", sharedCounter);
                                

Because there is only one underlying variable — not a separate copy per file — the value is 12 everywhere.

6. What if I forget the definition?

undefined reference to 'sharedCounter'
                                

This is the classic extern error. The compiler accepted every extern declaration, but no file actually created the variable, so the linker has nothing to connect them to. Fix: add one definition (without extern) in a single .c file.

🎯 Remember this: extern is a promise you make to the compiler — "don't worry, the variable exists elsewhere". If you break that promise (no definition anywhere), the linker complains. One definition, many declarations — that's the whole rule.

Frequently Asked Questions

1. What's the difference between a declaration and a definition?

A declaration says "this name exists and has this type" — it doesn't create storage. A definition actually creates the storage. So extern int x; is a declaration, and int x = 0; is a definition. Every definition is also a declaration, but not the other way around.

2. Can I define the same variable twice?

No. In modern C (with GCC or Clang), two definitions of the same global is a linker error: "multiple definition of 'x'". You must have exactly one definition and any number of extern declarations. (Older compilers sometimes allowed this with a "common symbol" extension, but don't rely on it.)

3. When should I use extern instead of static?

Use extern when the variable needs to be shared between files. Use static (at file scope) when you want a global that is only visible inside one file — that's safer and should be your default. Only lift a variable to extern visibility if another file genuinely needs it.

4. Do I need to put extern declarations in a header file?

It's a good idea. Put extern int sharedCounter; in globals.h and include that header from every .c file that needs the variable. That keeps declarations consistent — if the type ever changes, you update one line, not five.

5. Why do I sometimes see "tentative definition" warnings?

If you write int x; (no initializer, no extern) at file scope in two files, older compilers treat both as "tentative" definitions and merge them — which is non-standard behavior. Modern compilers with -fno-common (now the default on GCC 10+) reject this. Fix: put the real definition in one file and extern in the others.

💡 Tip: Run nm on your compiled object files to see what symbols each one defines and needs. U means undefined (needs extern), D means defined. That's the fastest way to debug link errors.

📖 Related Tutorials

  • Storage Classes in C — Full Tutorial
  • 1. auto Storage Class
  • 2. register Storage Class Performance
  • 3. static Storage Class State
  • 10. Global Variables Across Files with extern
  • All Storage Class Assignments

Previous Topic: -->> 3. static Storage Class State   ||   Next topic: -->> 5. typedef with Complex Data Type


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.