根据C标准:
In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.
在我的示例中,我们有三个单独的声明,每个标识符都有不同的链接。那么为什么这行不通呢?
static int a; //a_Internal
int main(void) {
int a; //a_Local
{
extern int a; //a_External
}
return 0;
}
错误:
In function 'main': Line 9: error: variable previously declared 'static' redeclared 'extern'
为什么编译器坚持要我重新声明而不是尝试访问另一个文件中的外部对象?
供引用的有效 C++ 示例:
static void f();
static int i = 0; // #1
void g() {
extern void f(); // internal linkage
int i; // #2 i has no linkage
{
extern void f(); // internal linkage
extern int i; // #3 external linkage
}
}
Clang 和 VC 似乎都适合我的 C 示例;只有某些版本的 GCC(不是全部)会产生上述错误。
最佳答案
§6.2.2, 7 说:
If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.
所以,你的程序有undefined behaviour .
§6.2.2, 4 说
extern int a; //a_External
具有外部链接,因为先前的声明在范围 int a 中可见;//a_Local
没有链接。但是
static int a; //a_Internal
声明带有内部链接的a
。因此,根据 §6.2.2, 7,它未定义。
关于c - 外部、内部且没有链接,或者为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39767348/