static function in C

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

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

相关标签:
7条回答
  • 2020-11-30 17:42

    Looking at the posts above I would like to give a more clarified answer:

    Suppose our main.c file looks like this:

    #include "header.h"
    
    int main(void) {
        FunctionInHeader();
    }
    

    Now consider three cases:

    • Case 1: Our header.h file looks like this:

       #include <stdio.h>
      
       static void FunctionInHeader();
      
       void FunctionInHeader() {
           printf("Calling function inside header\n");
       }
      

      Then the following command on linux:

       gcc main.c -o main
      

      will succeed! That's because after the main.c file includes the header.h, the static function definition will be in the same main.c file (more precisely, in the same translation unit) to where it's called.

      If one runs ./main, the output will be Calling function inside header, which is what that static function should print.

    • Case 2: Our header header.h looks like this:

        static void FunctionInHeader();     
      

      and we also have one more file header.c, which looks like this:

        #include <stdio.h>
        #include "header.h"
      
        void FunctionInHeader() {
            printf("Calling function inside header\n");
        }
      

      Then the following command

        gcc main.c header.c -o main
      

      will give an error. In this case main.c includes only the declaration of the static function, but the definition is left in another translation unit and the static keyword prevents the code defining a function to be linked

    • Case 3:

      Similar to case 2, except that now our header header.h file is:

        void FunctionInHeader(); // keyword static removed
      

      Then the same command as in case 2 will succeed, and further executing ./main will give the expected result. Here the FunctionInHeader definition is in another translation unit, but the code defining it can be linked.

    Thus, to conclude:

    static keyword prevents the code defining a function to be linked,
    when that function is defined in another translation unit than where it is called.
    
    0 讨论(0)
提交回复
热议问题