0
0
Power-electronicsConceptBeginner · 3 min read

What is static keyword in Embedded C: Explanation and Examples

In Embedded C, the static keyword limits the scope of a variable or function to the file or block where it is declared, preventing access from other files. It also preserves the value of a variable between function calls by allocating it in static memory instead of the stack.
⚙️

How It Works

Think of the static keyword as a way to keep things private and lasting inside your program. When you declare a variable or function as static inside a file, it becomes invisible to other files, like a secret note only you can read. This helps avoid confusion or mistakes when many parts of a program use the same names.

Also, when you use static inside a function for a variable, it remembers its value even after the function finishes. Imagine a jar that keeps its contents safe between visits instead of emptying every time you leave. This is useful in embedded systems where you want to keep track of states or counts without using global variables.

💻

Example

This example shows a static variable inside a function that counts how many times the function is called. The value stays saved between calls.

c
#include <stdio.h>

void countCalls() {
    static int count = 0;  // This variable keeps its value
    count++;
    printf("Function called %d times\n", count);
}

int main() {
    countCalls();
    countCalls();
    countCalls();
    return 0;
}
Output
Function called 1 times Function called 2 times Function called 3 times
🎯

When to Use

Use static in Embedded C when you want to keep data private to a file or function and avoid accidental changes from other parts of your program. It is great for:

  • Keeping track of counts or states inside a function without globals.
  • Limiting the visibility of helper functions or variables to one file, improving modularity.
  • Saving memory by avoiding unnecessary global variables.
  • Ensuring data persists between function calls in embedded systems where resources are limited.

Key Points

  • static limits scope to the file or function where declared.
  • Static variables inside functions keep their value between calls.
  • Static functions and variables are not visible outside their source file.
  • Helps manage memory and avoid naming conflicts in embedded projects.

Key Takeaways

The static keyword restricts variable or function visibility to the current file or function.
Static variables inside functions retain their value between calls, unlike normal local variables.
Use static to keep data private and persistent without using global variables.
Static helps avoid naming conflicts and improves modularity in embedded C programs.