What is a “static” function in C?

前端 未结 12 1205
野的像风
野的像风 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:23

    Minor nit: static functions are visible to a translation unit, which for most practical cases is the file the function is defined in. The error you are getting is commonly referred to as violation of the One Definition Rule.

    The standard probably says something like:

    "Every program shall contain exactly one definition of every noninline function or object that is used in that program; no diagnostic required."

    That is the C way of looking at static functions. This is deprecated in C++ however.

    In C++, additionally, you can declare member functions static. These are mostly metafunctions i.e. they do not describe/modify a particular object's behavior/state but act on the whole class itself. Also, this means that you do not need to create an object to call a static member function. Further, this also means, you only get access to static member variables from within such a function.

    I'd add to Parrot's example the Singleton pattern which is based on this sort of a static member function to get/use a single object throughout the lifetime of a program.

提交回复
热议问题