0
0
Power-electronicsConceptBeginner · 3 min read

What is extern keyword in Embedded C: Explanation and Example

In Embedded C, the 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.

c
// 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;
}
Output
Value is: 10 Value is: 20
🎯

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

  • extern declares 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 extern references to actual definitions.

Key Takeaways

The extern keyword declares variables or functions defined in other files.
It enables sharing of data and code across multiple source files in embedded C.
Use extern to avoid duplicate definitions and keep code modular.
The linker connects extern declarations to their actual definitions at build time.