我有两个文件。第一个 a.c
有
extern int i;
int main()
{
i = 5;
printf("i=%d",i);
}
另一个文件b.c
有
struct i
{
int a;
int b;
}
当编译这两个文件并链接它们时,我得到i=5
作为输出。
为什么会发生这种情况? i
在 a.c
和 b.c
中具有单独的类型。
最佳答案
在 C 语言中,相同标识符的不同出现可能具有不同的值 相同编译单元中的类型(不用介意链接)。这 程序没问题:
#include <stdio.h>
struct i
{
int i;
};
static int i;
int main(void)
{
i = 1;
struct i ii;
ii.i = i;
printf("%d\n",ii.i);
return 0;
}
根据 C99,结构标记和变量名称位于不同的命名空间中 标准:
6.2.3 标识符的命名空间
If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. Thus, there are separate name spaces for various categories of identifiers, as follows:
— label names (disambiguated by the syntax of the label declaration and use);
— the tags of structures, unions, and enumerations (disambiguated by following any of the keywords struct, union, or enum);
— the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access the member via the . or -> operator);
— all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).
(该程序也是合法的 C++,将 <stdio.h>
替换为 <cstdio>
)
关于c - 链接时允许不同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23855782/