因此,在AFAIK中,您可以根据需要在C中声明一个名称多次,但是不能多次定义一个名称。同样根据我的想法,声明是指引入名称时。比方说,编译器会将名称添加到符号表中。定义是何时为名称分配内存。现在,在这里再次声明名称 p 。不再定义。
#include <iostream>
#include <cmath>
float goo(float x)
{
int p = 4;
extern int p;
cout << p << endl;
return floor(x) + ceil(x) / 2;
}
int p = 88;
但是,出现以下错误:
iter.cpp: In function ‘float goo(float)’:
iter.cpp:53:16: error: redeclaration of ‘int p’
extern int p;
^
iter.cpp:52:9: note: previous declaration ‘int p’
int p = 4;
据我说,
int p = 4;
应该在调用堆栈上为p分配内存,即引入一个新的局部变量。然后,extern int p应该再次声明p。现在p应该引用全局变量p,并且该p应该在goo函数的所有后续语句中使用。
最佳答案
you can declare a name in C as many times as you want, but you cannot redefine a name more than once.
这是错误的,或者至少是不完整的。如果在同一范围内有多个使用相同名称的声明,则它们都必须声明相同的内容。例如,您不能声明
p
同时是本地变量的名称和外部变量的名称。如果要对不同的事物使用相同的名称,则声明必须在不同的范围内。例如
{
int p = 4;
{
extern int p;
extern int p; // Declare the same thing twice if you want.
std::cout << p << std::endl;
}
return floor(x) + ceil(x) / 2;
}
对两个不同的变量使用名称
p
,并使用不同的范围来区分这些含义。因此,这不再是错误。这是不可取的,因为这会使人类程序员感到困惑,但是就编译器而言,这是可以接受的。
关于c++ - 使用extern时C++中的重新声明错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61416175/