Storage Class: extern — Sharing Globals Across Files
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Manage Global Variables Across Multiple Files Using extern

📑 On this page:
  • Why extern for Global Variables?
  • Definition vs Declaration
  • Complete Multi-File C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • The difference between a definition and an extern declaration
  • How to share one global variable across multiple .c files
  • Why the header file should contain only extern declarations
  • How the linker resolves extern references to a single definition
  • Common linker errors: multiple definition and undefined reference

Why extern for Global Variables?

In a multi-file C project, you often need one piece of state — a configuration value, a shared counter, a global logger handle — that several .c files must read and write. If you define that variable in a header and include the header in three files, you get three separate copies (or, worse, a linker error for duplicate definitions). If you define it in one file but try to use it in another, the compiler doesn't know the name exists.

The solution is the extern keyword. It tells the compiler: "This variable exists somewhere — trust me, the linker will find it." You write the actual definition exactly once, in one .c file. Everywhere else, you declare it with extern (usually in a shared header) and the compiler compiles each file happily. The linker then stitches them together into one program with one shared variable.

💡 In one line: extern says "I promise this variable exists somewhere else." You define it once; you declare it everywhere you use it.

C program sharing a global variable across multiple files using extern declarations in a header

Definition vs Declaration

Concept Syntax Allocates memory? How many allowed?
Definitionint count = 0;YesExactly one per program
Declaration (extern)extern int count;NoAs many as you like
Tentative definitionint count; (at file scope)Yes (become definition if no other)One per program

Rule of thumb: define once in a .c file, declare extern in a .h file, include the header wherever the variable is used.

Complete Multi-File C Program

This project is three files plus a header. Save them in the same directory, then compile them together.

File 1: shared.h — the header with the extern declaration

#ifndef SHARED_H
#define SHARED_H

/* Declaration only — no memory is allocated here */
extern int shared_counter;
extern long shared_total;

/* Functions implemented in shared.c */
void add_to_total(int value);
void print_status(void);

#endif /* SHARED_H */
                                    

File 2: shared.c — the single definition lives here

#include <stdio.h>
#include "shared.h"

/* THE definition — this is the one place storage is created */
int shared_counter = 0;
long shared_total = 0;

void add_to_total(int value) {
    shared_counter++;            /* bump call count */
    shared_total += value;       /* accumulate value */
}

void print_status(void) {
    printf("shared_counter = %d, shared_total = %ld\n",
           shared_counter, shared_total);
}
                                    

File 3: main.c — uses the shared variables via the header

#include <stdio.h>
#include "shared.h"

int main(void) {
    int i;

    /* Write directly to the shared global */
    shared_counter = 10;

    /* Use the helper functions that also touch the globals */
    for (i = 1; i <= 4; i++) {
        add_to_total(i * 25);
    }

    /* Read the shared values back */
    printf("After add_to_total calls:\n");
    print_status();

    /* Modify directly from main and show it's the same object */
    shared_counter = 99;
    shared_total  = 12345;

    printf("\nAfter direct writes in main:\n");
    print_status();

    return 0;
}
                                    

Compile and run

gcc main.c shared.c -o program
./program
                                    

Program Output

After add_to_total calls:
shared_counter = 14, shared_total = 250

After direct writes in main:
shared_counter = 99, shared_total = 12345
                                

Here's what to notice. main.c set shared_counter = 10. Then add_to_total — a function living in a different source file — incremented the same variable four times, ending at 14. If the two files had separate copies, shared_counter would still be 10. It isn't — proof that both files are talking about the same object. The final direct write of 99 shows up in print_status() as well.

Step-by-Step Explanation

Let's trace exactly how the compiler and linker cooperate to make this work.

1. shared.c allocates the memory:

int shared_counter = 0;
long shared_total = 0;
                                

These lines are a definition. The compiler reserves 4 bytes for shared_counter (assuming 32-bit int) and 8 bytes for shared_total, initializes them to zero, and exports their symbols from shared.o.

2. shared.h only declares them:

extern int shared_counter;
extern long shared_total;
                                

The extern keyword tells the compiler: "Do not allocate storage. Just record that a variable with this name and type exists. Leave the address for the linker to fill in." Every file that includes shared.h gets this declaration, and the compiler never complains about duplicated definitions — because none of these are definitions.

3. main.c uses them:

shared_counter = 10;
add_to_total(25);
print_status();
                                

When the compiler processes main.c, it sees the extern declarations, so it knows shared_counter is an int. It generates code to write to it and leaves a relocation entry — a placeholder that says "fill in the real address later."

4. The linker resolves the placeholders:

When you run gcc main.c shared.c -o program, the compiler produces two object files, main.o and shared.o. The linker scans both, finds the definitions of shared_counter and shared_total in shared.o, and patches every reference in main.o to point to those addresses. One variable, two files, seamless.

5. What if you slip up?

  • Two definitions: If you write int shared_counter = 0; in both main.c and shared.c, the linker complains: multiple definition of 'shared_counter'. That's the most common extern mistake.
  • No definition: If you forget to define it in any file — only the extern declarations exist — the linker fails with undefined reference to 'shared_counter'.
  • Forgot the header: If main.c uses shared_counter but doesn't #include "shared.h", the compiler errors with 'shared_counter' undeclared. The extern declaration is how the compiler learns the name.

6. Why not put the definition in the header?

Because headers are copied into every file that includes them. If shared.h contained int shared_counter = 0;, then main.c and shared.c would each produce their own definition, and the linker would refuse to build. The header/implementation split is precisely what extern enables. (C23 also introduces a static inline / constexpr path, but for mutable global state, extern remains the standard idiom.)

🎯 Remember this: One definition, many extern declarations. Define in a .c file; declare in a .h file; include the header wherever you need the name. If the linker ever complains about duplicates, you defined it twice.

Frequently Asked Questions

1. Can I use extern for functions too?

Yes. extern int add(int a, int b); is a function declaration — but in C, function declarations are extern by default, so the keyword is redundant. You'll see it used occasionally for clarity. For variables, the keyword is essential: int count; at file scope is a (tentative) definition, while extern int count; is not.

2. What's the "tentative definition" rule?

At file scope, int count; without an initializer is a tentative definition — the compiler allows it, treating it as a declaration until it finds a real definition. If none appears, the tentative definition becomes the real one and the variable is zero-initialized. If you want to be unambiguous, use extern int count; in headers and int count = 0; in exactly one .c file.

3. Does extern initialize the variable?

No. An extern declaration with an initializer (extern int x = 5;) is technically a definition, not a declaration — avoid it in headers, since every file that includes the header creates a definition. Put the initializer only in the single defining .c file.

4. Can I use extern on a static variable?

No, and it would be contradictory. static at file scope means internal linkage — the variable is private to that file. extern asks for external linkage — the variable is visible across files. You can't have both. Attempting extern static int x; is an error in most compilers.

5. Are shared globals thread-safe?

No. Any variable visible across files and modifiable by multiple threads is a data race waiting to happen. If two threads call add_to_total() simultaneously, they can both read the old shared_counter and write the same incremented value, losing updates. Protect the access with a mutex or use C11 atomics (atomic_int, atomic_fetch_add).

6. Is extern considered good practice?

It's the traditional tool, but many modern guidelines discourage mutable global state altogether because it makes code harder to test and reason about. Alternatives include passing a shared context struct as a parameter, using an accessor function (int *global_counter(void)), or hiding the variable behind a module API. When you do need extern, keep the shared variable's type documented and its accessor functions tightly controlled.

💡 Tip: Name your defining file after the module (e.g., shared.c for shared.h) and keep the definition right at the top. When the "multiple definition" linker error hits, the message usually names the offending files — search them for the variable name and delete the duplicate.

📖 Related Tutorials

  • Storage Classes in C — Full Tutorial
  • extern Storage Class — Complete Guide
  • 9. Static Unique Identifiers
  • 8. register Variables in Large Datasets
  • All Storage Class Assignments

Previous Topic: -->> 9. Static Unique Identifiers   ||   Next topic: -->> All Storage Class Assignments


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.