【问题标题】:Using extern keyword to call functions使用 extern 关键字调用函数
【发布时间】:2017-08-28 15:59:14
【问题描述】:

我想从 other.c 调用 test.c 中定义的函数。

我可以externfunction1 打电话吗?另外,我必须在function2function3 中使用extern,它们被function1 调用吗?

other.c

extern function1();
function1();

test.c

void function1()
{
    function2();
    function3();
}

void function2()
{

}

void function3()
{

}

【问题讨论】:

  • void function1();替换extern function1();
  • ...不,如果您不想从other.c 呼叫它们,则无需关心function2()function3()
  • 我明白了。我希望 function1 能够调用它们,它应该能够调用它们,对吗?
  • 正常的做法是创建other.h,并把void function1()放在那里。然后 #include other.h 在 test.c
  • extern 只有共享数据需要,函数不需要

标签: c extern storage-class-specifier


【解决方案1】:

函数声明是“默认”extern

引用C11,第 §6.2.2 章,(强调我的

如果函数的标识符声明没有存储类说明符,则其链接 完全确定就像使用存储类说明符 extern 声明一样。 [...]

因此,您无需明确说明。

您需要编译翻译单元,即源文件(到目标文件),然后将它们链接在一起以构建可执行文件。应该这样做。

【讨论】:

    【解决方案2】:

    extern 只是告诉我们它是在其他地方定义的。您正在编写extern 的文件中使用它。但是函数默认是外部的。所以你不需要明确说明。

    【讨论】:

    • @PeterJ_01.:我勇敢地解释了更多关于对象以显示差异?如果你告诉我他们不符合这个答案,我可以删除
    【解决方案3】:

    实际上,默认情况下每个函数都是 extern :) - 除非您声明它们不是 :)。如果你在第一次调用之前有原型就足够了;

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

    函数可以在另一个 .c 文件中。您需要在链接中包含目标文件。

    int xxx(int a, int b, float c, double d)
    {
      int result;
      /* do something */
    
      return result;
    }
    

    【讨论】:

    • @Filip Kočica :( 。如果你这样做了,你就知道你想要归档什么。评论完全离题了
    【解决方案4】:

    您使用extern 来声明当前translation unit外部 符号(大致是一个包含所有头文件的单个源文件)。

    简单示例

    第一个源文件test1.c

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

    然后是第二个源文件test2.c

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

    如您所见,函数 function2 在任何地方都不需要任何 extern 声明。它仅用于test2.c,因此只有function1 需要了解它。

    但是在test1.c 中,main 函数需要知道function1,因为它被调用了,然后我们对函数原型进行前向声明。这是使用extern 关键字完成的。 但是对于声明函数,实际上并不需要 extern 关键字,因为它们总是被认为是“外部的”(如 Peter 所述)。

    【讨论】:

    • 函数总是外部的。变量不是。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    相关资源
    最近更新 更多