Using extern keyword to call functions

后端 未结 4 1341
借酒劲吻你
借酒劲吻你 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:11

    Actually every function by default is extern :) - unless you declare them to be not :). It is enough if you have the prototype before the first call;

    int xxx(int, int, float, double);  // prototype
    
    
    int main(void)
    {
      int x,y;
      float z;
      double v;
    
      xxx(x,y,z,v);
    
      return 0;
    }
    

    Function can be in the another .c file. You need to include the object file to the linking.

    int xxx(int a, int b, float c, double d)
    {
      int result;
      /* do something */
    
      return result;
    }
    
    0 讨论(0)
  • 2021-01-21 22:13

    extern simply tells us that it is defined somewhere else. And you are using it in the file you are writing the extern. But functions are by default extern. So you need not be explicit about it.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-21 22:19

    Function declarations are "by-default" extern.

    Quoting C11, chapter §6.2.2, (emphasis mine)

    If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. [...]

    So, you don't need to be explicit about it.

    You need to compile the translation units aka source files (into object files) and then link them together to build the executable. That should do it.

    0 讨论(0)
提交回复
热议问题