Why declare a variable or function static in C?

前端 未结 4 1792
小鲜肉
小鲜肉 2020-12-18 19:25

I understand what static does, but not why we use it. Is it just for keeping the abstraction layer?

4条回答
  •  天涯浪人
    2020-12-18 19:49

    static is used as both a storage class specifier and a linkage specifier. As a linkage specifier it restricts the scope of an otherwise global variable or function to a single compilation unit. This allows, for example a compilation unit to have variables and functions with the same identifier names as other compilation units but without causing a clash, since such identifiers are 'hidden' from the linker. This is useful if you are creating a library for example and need internal 'helper' functions that must not cause a conflict with user code.

    As a storage class specifier applied to a local variable, it has different semantics entirely, but your question seems to imply that you are referring to static linkage.

提交回复
热议问题