根据维基百科:
http://en.wikipedia.org/wiki/External_variable
外部变量也可以在函数内部声明。
在函数中声明外部变量的目的是什么?它也必须是静态的吗?
它允许将对全局的访问限制在某个范围内:
int main()
{
extern int x;
x = 42; //OKAY
}
void foo()
{
x = 42; //ERROR
}
int x;
外部声明进入函数内部。它只是意味着没有其他函数可以看到该变量。
void func()
{
extern int foo;
foo ++;
}
void func2()
{
foo--; // ERROR: undeclared variable.
}
在另一个源文件中:
int foo; // Global variable. Used in the other source file,
// but only in `func`.
这只是一种“隔离”变量的方法,因此它不会意外地在不应该使用的地方使用。
在命名空间范围内声明外部变量的唯一区别:
extern int x;
void foo() {
cout << x;
}
并在函数范围内声明它:
void foo() {
extern int x;
cout << x;
}
是在后一种情况下,x
仅在函数内部可见。
你所做的只是进一步收紧extern
声明的范围。
这是一个使用命名空间的类似示例:
在命名空间范围内:
#include <string>
using std::string;
void foo() {
string str1;
}
string str2; // OK
在功能范围内:
#include <string>
void foo() {
using std::string;
string str1;
}
string str2; // Error - `using` not performed at this scope
文本指的是函数内部外部变量的非定义声明。函数内部的外部定义是非法的。
因此,在函数内部对 extern 变量进行非定义声明仅仅意味着您想在该函数内部使用该变量。变量本身必须是在别处定义的全局变量。
基本上,如果您不需要在整个翻译单元中访问该全局变量(在其他地方定义)并且只需要在该函数中使用它,那么在本地声明它是一个非常好的主意。这样,您就不会使用其他功能不需要的标识符来污染全局命名空间。
extern
关键字表示标识符具有外部链接。这意味着它在使用外部链接声明的其他任何地方都链接到相同的名称。也就是说,不同地方的名称的不同实例指的是同一个对象。
在块(包括定义函数的块)内声明标识符为其赋予块范围。该标识符实例的范围在块的末尾结束。
结合extern
块作用域允许函数查看外部标识符,而不会弄乱其他函数的名称空间。(尽管如此,这通常是不好的做法。)