【问题标题】:Why declaration by 'extern' doesn't work with static functions in C?为什么'extern'声明不适用于C中的静态函数?
【发布时间】:2012-12-09 13:55:10
【问题描述】:

假设代码:

extern int foo(void);

static int foo(void)
{
        return 0;
}

尝试用 GCC 编译

$ gcc -Wall -std=c99 1.c 
1.c:3:12: error: static declaration of ‘foo’ follows non-static declaration
1.c:1:12: note: previous declaration of ‘foo’ was here
1.c:3:12: warning: ‘foo’ defined but not used [-Wunused-function]

那么,我该如何声明静态函数呢?

【问题讨论】:

  • "那么,如何声明静态函数?" static int foo(void);

标签: c static extern


【解决方案1】:

为什么extern 的声明不适用于static 函数?

因为extern 表示外部链接,而static 表示内部链接。显然,你不能同时拥有相同的功能。

简单来说,当您在函数上使用static 时,您告诉编译器请将此函数的范围仅限于此translation unit,并且不允许任何人从其他人访问它翻译单元。
虽然函数声明默认为 extern,但当您明确指定 extern 时,您会告诉编译器,请允许其他翻译单元的所有人访问此函数。
很明显,编译器不能同时做这两件事。

因此,请做出选择,您是否希望该功能仅在翻译单元中可见。
如果前者是 static 并忘记 extern。如果后者只是删除static

好读:
What is external linkage and internal linkage?

虽然上面的 Q 是针对 C++ 的,但所讨论的大部分内容也适用于 C。

【讨论】:

  • 感谢您的精彩回答!
  • 在你看来,为什么静态声明后跟非静态是允许的?
【解决方案2】:

你用static声明它

static int foo(void);

static int foo(void)
{
        return 0;
}

【讨论】:

    【解决方案3】:

    extern 表示函数在不同的翻译单元(文件)中定义。 static 表示仅在定义它的翻译单元中使用。两者互斥。

    【讨论】:

      【解决方案4】:

      不是说静态可以用extern(al)这样的链接来解决吗 文件1.c

      static int fx(void)
      {
          return int;
      }
      

      文件2.c

      extern int fx(void);
      
      /*call */
      fx();
      

      【讨论】:

      • 如果在符号表中找不到静态,只需将 extern 放入 REDEFINITION 即可解决。在大多数情况下,链接器会解决它。尽管静态的简单定义是它具有内部链接范围。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      • 2019-08-03
      • 2010-09-24
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      相关资源
      最近更新 更多