c++ - 使用extern时C++中的重新声明错误

标签 c++ compiler-errors scope global-variables forward-declaration

因此,在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/

相关文章:

c++ - 忽略函数默认参数

c++ - 在类函数中初始化字符串数组

c++ - C++ 中共享库主头文件的最佳实践是什么?

swift 3、iOS 10 - 错误 : Thread 1 Signal Sigabrt (SPRITEKIT)

javascript - 函数的变量范围

c++ - 在 C++ 中隐藏 int 变量的名称

c++ - 为什么 C++ 20 中没有枚举概念?

c++ - 在类之间传递多维数组

visual-studio - Microsoft Multilingual非法字符在构建路径上

javascript - javascript : when nested function is defined or executed? 闭包什么时候捕获变量值(在外部函数中定义)