乐闻世界logo
搜索文章和话题

What is the difference between static and extern in C?

1个答案

1

In C, the static and extern keywords define the scope (visibility) and lifetime of variables or functions. Different usage patterns have distinct effects on program behavior.

static keyword

The static keyword serves two primary purposes:

  1. Limiting scope: When static is applied to a variable within a function, it extends the variable's lifetime to span the entire program execution while keeping its scope confined to the function where it is defined. Such variables are termed static local variables. The value of a static local variable persists across function calls, rather than being reinitialized.

    Example:

    c
    void function() { static int count = 0; // Initialized on first call and retains value in subsequent calls count++; printf("This function has been called %d times\n", count); }

    Here, each invocation of function retains and increments count's value.

  2. Limiting linkage: When static is used for a global variable or function, it modifies the linkage property, making them visible only within the file where they are defined and inaccessible to other files. This helps avoid name collisions and ensures data encapsulation and hiding.

    Example:

    c
    static int value = 5; // Cannot be accessed from other files static void secretFunction() { printf("This is an internal function, not visible externally\n"); }

    Both value and secretFunction are inaccessible outside their defining source file.

extern keyword

The extern keyword declares a global variable or function whose definition resides in another file. It informs the compiler that the symbol is defined elsewhere, enabling sharing of global variables or functions across multiple files in a multi-file project.

  1. Referencing symbols in other files: extern signals to the compiler that a symbol is defined in another file.

    Example:

    c
    // Defined in file1.c int globalVar = 100; // Declared and used in file2.c extern int globalVar; void useGlobalVar() { printf("globalVar = %d\n", globalVar); }

    In this case, globalVar is defined in file1.c and declared/used in file2.c.

Summary

  • Using static restricts the scope of variables or functions and maintains the persistence of local variables.
  • Using extern enables sharing of variables or functions across multiple files, enhancing code modularity and reusability.

These keywords are critical for managing data and function access permissions in large-scale software projects.

2024年6月29日 12:07 回复

你的答案