假设代码:
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]
那么,我该如何声明静态函数呢?
最佳答案
Why declaration by
extern
doesn't work withstatic
functions?
因为extern
表示外部链接,而static
表示内部链接。显然,您不能同时具有相同的功能。
简单来说,当您在函数上使用 static
时,您告诉编译器请将此函数的范围限制在 translation unit 内 并且不允许任何人从另一个翻译单元访问它。
虽然默认情况下函数声明是 extern
,但当您明确指定 extern
时,您告诉编译器,请允许其他翻译单元的每个人访问此函数。
很明显,编译器不能同时做到这两点。
所以做出选择,是否希望该功能仅在翻译单元中可见。
如果前者使它成为 static
而忘记 extern
。如果后者只是删除 static
。
好读:
What is external linkage and internal linkage?
虽然上面的 Q 是针对 C++ 的,但讨论的大部分内容也适用于 C。
关于c - 为什么 'extern' 的声明不适用于 C 中的静态函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13788035/