What is extern keyword in C: Explanation and Examples
extern keyword in C tells the compiler that a variable or function is defined in another file or location. It is used to declare a variable or function without allocating memory, allowing sharing across multiple files.How It Works
Imagine you have a toolbox shared among friends. Instead of each friend buying the same tool, they just say, "I have that tool in my toolbox," and use it when needed. In C, extern works like that: it tells the program "This variable or function exists somewhere else, so don't create a new one here."
This helps when you split your program into multiple files. One file can define a variable or function, and others can use extern to access it without making copies. The compiler then links these references to the original definition during the linking step.
Example
This example shows how extern lets two files share a variable.
// file1.c #include <stdio.h> int count = 5; // Define variable void printCount() { printf("Count is %d\n", count); } // file2.c #include <stdio.h> extern int count; // Declare variable defined elsewhere extern void printCount(); // Declare function defined elsewhere int main() { printCount(); count = 10; // Change the shared variable printCount(); return 0; }
When to Use
Use extern when you want to share variables or functions between different files in a program. For example, if you have a global configuration or a shared counter used by many parts of your program, define it once and declare it with extern elsewhere.
This keeps your code organized and avoids duplicate variables, which can cause errors or unexpected behavior.
Key Points
externdeclares a variable or function without defining it.- It tells the compiler the actual definition is in another file.
- Helps share data and functions across multiple source files.
- Does not allocate memory by itself.
- Used mainly for global variables and functions.
Key Takeaways
extern declares variables or functions defined elsewhere to share them across files.extern does not allocate memory; only the original definition does.extern for global variables or functions accessed in multiple files.