What is extern keyword in Embedded C: Explanation and Example
extern keyword declares a variable or function that is defined in another file or location. It tells the compiler that the actual storage or code exists elsewhere, allowing multiple files to share the same variable or function.How It Works
Think of extern as a way to say "This thing exists somewhere else." Imagine you have a toolbox in one room and you want to use a tool from it in another room without carrying it around. Instead, you just say where the tool is kept. Similarly, extern tells the compiler that a variable or function is declared in another file or place, so it doesn't create a new copy but uses the original.
In embedded systems, programs often split into multiple files for better organization. Using extern helps share variables or functions across these files without duplication. The linker later connects these references to the actual definitions, ensuring the program works as one unit.
Example
This example shows how to use extern to share a variable between two files.
// file1.c #include <stdio.h> int sharedValue = 10; // Definition of shared variable void printValue() { printf("Value is: %d\n", sharedValue); } // file2.c #include <stdio.h> extern int sharedValue; // Declaration using extern void changeValue() { sharedValue = 20; // Modify the shared variable } // main.c void printValue(); void changeValue(); int main() { printValue(); // Prints 10 changeValue(); printValue(); // Prints 20 return 0; }
When to Use
Use extern when you want to access a variable or function defined in another file. This is common in embedded projects where code is split into modules, like separating hardware control and application logic.
For example, if you have a global configuration variable or a hardware status flag defined in one file, other files can use extern to read or modify it without redefining it. This keeps your code organized and avoids multiple copies of the same data.
Key Points
externdeclares a variable or function without defining it.- It tells the compiler the actual definition is elsewhere.
- Helps share data and functions across multiple files.
- Used heavily in embedded C for modular code design.
- Linker resolves
externreferences to actual definitions.