What is a “static” function in C?

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

    The following is about plain C functions - in a C++ class the modifier 'static' has another meaning.

    If you have just one file, this modifier makes absolutely no difference. The difference comes in bigger projects with multiple files:

    In C, every "module" (a combination of sample.c and sample.h) is compiled independently and afterwards every of those compiled object files (sample.o) are linked together to an executable file by the linker.

    Let's say you have several files that you include in your main file and two of them have a function that is only used internally for convenience called add(int a, b) - the compiler would easily create object files for those two modules, but the linker will throw an error, because it finds two functions with the same name and it does not know which one it should use (even if there's nothing to link, because they aren't used somewhere else but in it's own file).

    This is why you make this function, which is only used internal, a static function. In this case the compiler does not create the typical "you can link this thing"-flag for the linker, so that the linker does not see this function and will not generate an error.

提交回复
热议问题