static function in C

前端 未结 7 1601
天涯浪人
天涯浪人 2020-11-30 17:11

What is the point of making a function static in C?

7条回答
  •  孤城傲影
    2020-11-30 17:33

    Making a function static hides it from other translation units, which helps provide encapsulation.

    helper_file.c

    int f1(int);        /* prototype */
    static int f2(int); /* prototype */
    
    int f1(int foo) {
        return f2(foo); /* ok, f2 is in the same translation unit */
                        /* (basically same .c file) as f1         */
    }
    
    int f2(int foo) {
        return 42 + foo;
    }
    

    main.c:

    int f1(int); /* prototype */
    int f2(int); /* prototype */
    
    int main(void) {
        f1(10); /* ok, f1 is visible to the linker */
        f2(12); /* nope, f2 is not visible to the linker */
        return 0;
    }
    

提交回复
热议问题