What is a “static” function in C?

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

    Since static function is only visible in this file. Actually, compiler can do some optimization for you if you declare "static" to some function.

    Here is a simple example.

    main.c

    #include 
    
    static void test() 
    {
        ghost(); // This is an unexist function.
    }
    
    int main()
    {
        int ret = 0;
    
    #ifdef TEST
    #else
        test();
    #endif
        return (ret);
    } 
    

    And compile with

    gcc -o main main.c
    

    You will see it failed. Because you even not implement ghost() function.

    But what if we use following command.

    gcc -DTEST -O2 -o main main.c
    

    It success, and this program can be execute normally.

    Why? There are 3 key points.

    1. -O2 : Compiler optimization level at least 2.
    2. -DTEST : Define TEST, so test() will not be called.
    3. Defined "static" to test().

    Only if these 3 conditions are all true, you can pass compilation. Because of this "static" declaration, compiler can confirm that test() will NEVER be called in other file. Your compiler can remove test() when compiling. Since we don't need test(), it does not matter whether ghost() is defined or implemented.

提交回复
热议问题