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

标签 c linker

我有两个文件。第一个 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/

相关文章:

c++ - 静态和共享库符号冲突?

c - 链接器脚本 .relocate 部分的第一个符号 _srelocate 不正确(GCC 错误?)

c - RECV 动态内存分配

c - Rebol 3 扩展和 "handles"

linker - g++链接器无法识别-Bstatic

c++ - 对 __dso_handle_ 的 undefined reference - 在 cygwin 上编译 C++

c++ - 为第三方库 libA.a 包装对 malloc 的调用,但不为 libB.a 包装调用

c - OpenGL C - 我将如何从行星上绘制一条线迹?

c - 如何检查文件大小是否大于确定的数字?

c - 使用 C 中的函数从文件读取结构体数组