在C中声明两个同名的全局变量

时间:2021-12-08 09:32:41

I have declared two global variables of same name in C. It should give error as we cannot declare same name variables in same storage class.

我在C中声明了两个同名的全局变量。它应该给出错误,因为我们不能在同一个存储类中声明相同的名称变量。

I have checked it in C++ — it gives a compile time error, but not in C. Why?

我在C ++中检查过它 - 它给出了编译时错误,但不是在C中。为什么?

Following is the code:

以下是代码:

int a;
int a = 25;
int main()
{

   return 0;
}

Check it out at : Code Written at Ideone

请查看:Ideone撰写的代码

I think this probably is the reason

我想这可能就是原因

Declaration and Definition in C

C中的声明和定义

But this is not the case in C++. I think in C++, whether the variable is declared at global scope or auto scope the declaration and definition is happening at the same time.

但在C ++中并非如此。我认为在C ++中,无论变量是在全局范围还是自动范围声明,声明和定义都是同时发生的。

Could anyone throw some more light on it.

任何人都可以更多地关注它。

Now when I define the variable two times giving it value two times it gives me error (instead of one declaration and one definition).

现在当我定义变量两次给它两次值时,它给了我错误(而不是一个声明和一个定义)。

Code at : Two definitions now

代码:现在有两个定义

int a;
int a;
int a;
int a = 25;

int main()
{
return 0;
}

1 个解决方案

#1


8  

In C, multiple global variables are "merged" into one. So you have indeed just one global variable, declared multiple times. This goes back to a time when extern wasn't needed (or possibly didn't exist - not quite sure) in C.

在C中,多个全局变量被“合并”为一个。所以你确实只有一个全局变量,多次声明。这可以追溯到C.不需要extern(或者可能不存在 - 不太确定)的时候。

In other words, this is valid in C for historical reasons so that we can still compile code written before there was a ANSI standard for C.

换句话说,由于历史原因,这在C中是有效的,因此我们仍然可以编译在C标准之前编写的代码。

Although, to allow the code to be used in C++, I would suggest avoiding it.

虽然,为了允许代码在C ++中使用,我建议避免使用它。

#1


8  

In C, multiple global variables are "merged" into one. So you have indeed just one global variable, declared multiple times. This goes back to a time when extern wasn't needed (or possibly didn't exist - not quite sure) in C.

在C中,多个全局变量被“合并”为一个。所以你确实只有一个全局变量,多次声明。这可以追溯到C.不需要extern(或者可能不存在 - 不太确定)的时候。

In other words, this is valid in C for historical reasons so that we can still compile code written before there was a ANSI standard for C.

换句话说,由于历史原因,这在C中是有效的,因此我们仍然可以编译在C标准之前编写的代码。

Although, to allow the code to be used in C++, I would suggest avoiding it.

虽然,为了允许代码在C ++中使用,我建议避免使用它。