Using extern keyword to call functions

后端 未结 4 1346
借酒劲吻你
借酒劲吻你 2021-01-21 21:37

I want to call functions defined in test.c from other.c.

Can I extern the function1 to call it? Also, do I have to use extern in <

4条回答
  •  滥情空心
    2021-01-21 22:13

    You use extern to declare symbols which are external to the current translation unit (roughly a single source file with all its included header files).

    Simple example

    The first source file test1.c

    extern void function1(void);  // "Import" a function from another translation unit
    
    int main(void)
    {
        function1();  // Can call the declared function
    }
    

    Then the second source file test2.c:

    void function2(void)
    {
        // Do something
    }
    
    void function1(void)
    {
        function2();  // No extern needed, it's declared (and defined)
                      // in the same translation unit
    }
    

    As you can see the function function2 doesn't need any extern declaration anywhere. It is used only in test2.c so only function1 needs to know about it.

    However in test1.c the main function needs to know about function1 because it is called, then we make a forward declaration of the function prototype. This is done using the extern keyword. But for declaring functions the extern keyword isn't actually needed, as they are always considered "external" (as noted by Peter).

提交回复
热议问题