为什么我们不能在文件范围内两次键入一个(未命名的)结构,但是我们可以在没有错误的情况下两次输入"int"两次?

Sla*_*mac 2 c struct typedef

以下代码编译并运行正常:

#include <stdio.h>

typedef int Someint;
typedef int Someint;

int main()
{
    Someint b = 4;
    printf("%d", b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

以下代码无法编译.它给了我一个错误conflicting types for 'Somestruct'.

#include <stdio.h>

typedef struct
{
    int x;
}
Somestruct;

typedef struct
{
    int x;
}
Somestruct;

int main()
{
    Somestruct b;
    b.x = 4;
    printf("%d", b.x);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么我可以typedef 一次type(int在第一个代码中)两次没有错误,但同样的事情失败了另一个type(上面的结构)?这两种情况有什么区别?我正在使用CodeBlocks 12.11附带的MinGW编译器.

Ton*_*roy 6

当你做的时候:

typedef struct
{

} Somestruct;
Run Code Online (Sandbox Code Playgroud)

它创建了一个匿名结构 - 您可以期望使用一些隐藏的实现定义的保证唯一占位符标识符 - 您可以为其指定typedef.因此,当您执行两次时,您会遇到相同类型的名称要求引用两个不同结构的冲突.有了int,你只是重复原作.如果为结构提供实际名称,那么可以重复使用typedef:

typedef struct Somestruct
{

} Somestruct;
Run Code Online (Sandbox Code Playgroud)


Has*_*kun 5

因为您使用匿名结构定义了typedef,所以两个定义都是不同的.

以下不会这样做,并且有效.(请注意,您仍然只能定义struct一次)

#include <stdio.h>

typedef struct foo
{
    int x;
}
Somestruct;

typedef struct foo Somestruct;
Run Code Online (Sandbox Code Playgroud)