What is a “static” function in C?

前端 未结 12 1047
野的像风
野的像风 2020-11-22 16:03

The question was about plain c functions, not c++ static methods, as clarified in comments.

I understand what a static variable is, but wha

12条回答
  •  死守一世寂寞
    2020-11-22 16:16

    There are two uses for the keyword static when it comes to functions in C++.

    The first is to mark the function as having internal linkage so it cannot be referenced in other translation units. This usage is deprecated in C++. Unnamed namespaces are preferred for this usage.

    // inside some .cpp file:
    
    static void foo();    // old "C" way of having internal linkage
    
    // C++ way:
    namespace
    {
       void this_function_has_internal_linkage()
       {
          // ...
       }
    }
    

    The second usage is in the context of a class. If a class has a static member function, that means the function is a member of the class (and has the usual access to other members), but it doesn't need to be invoked through a particular object. In other words, inside that function, there is no "this" pointer.

提交回复
热议问题