c - 为什么 'extern' 的声明不适用于 C 中的静态函数?

标签 c static extern

假设代码:

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 with static 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/

相关文章:

c - 为什么 "const extern"报错?

c++ - 为什么不能使用外部常量定义数组?

javascript - ES6 : How to access a static getter from an instance

sql - Oracle OCI 错误 : Segmentation fault (core dumped) when fetching 100000 rows

c - 用 0 初始化整数与不在 C 中初始化它

python - 将其他 Cython 绑定(bind)对象传递给 Cython 绑定(bind)对象上的方法

c# - 静态方法中的全局变量

image - 静态图像的 OpenCV haar 训练

c - 为什么 'extern'存储类的功能不同?

objective-c - 在我的 xcode 项目中链接 c 语言文件时出现问题