gpt4 book ai didi

c - 链接时允许不同的类型

转载 作者:行者123 更新时间:2023-11-30 15:33:01 26 4
gpt4 key购买 nike

我有两个文件。第一个 a.c

extern int i;
int main()
{
i = 5;
printf("i=%d",i);
}

另一个文件b.c

struct i
{
int a;
int b;
}

当编译这两个文件并链接它们时,我得到i=5作为输出。

为什么会发生这种情况? ia.cb.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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com