姬長信(Redy)

c – 为什么在函数内初始化extern变量会产…


这段代码很好编译:
extern int i = 10;

void test()
{
    std::cout << "Hi" << i << std::endl;
}

虽然此代码给出了错误:

void test()
{
    extern int i = 10;
    std::cout << "Hi" << i << std::endl;
}

error: ‘i’ has both ‘extern’ and initializer

我在C++ Primer读到这个:

Any declaration that includes an explicit initializer is a definition.
We can provide an initializer on a variable defined as extern, but
doing so overrides the extern. An extern that has an initializer is a
definition. It is an error to provide an initializer on an extern inside a
function
.

有人可以提供一个解释,说明为什么这是一个错误,如果在函数本地完成,而在全局范围允许相同?