...
#include "test1.h"
int main(..)
{
count << aaa <<endl;
}
aaa
定义在test1.h
中,我没有使用extern关键字,但仍然可以引用aaa
。
所以我怀疑 extern
真的有必要吗?
最佳答案
extern
有其用途。但它主要涉及不受欢迎的“全局变量”。 extern
背后的主要思想是用外部链接来声明事物。因此,它有点与 static
相反。但在许多情况下,外部链接是默认链接,因此在这些情况下您不需要 extern
。 extern
的另一个用途是:它可以将定义变成声明。示例:
extern int i; // Declaration of i with external linkage
// (only tells the compiler about the existence of i)
int i; // Definition of i with external linkage
// (actually reserves memory, should not be in a header file)
const int f = 3; // Definition of f with internal linkage (due to const)
// (This applies to C++ only, not C. In C f would have
// external linkage.) In C++ it's perfectly fine to put
// somethibng like this into a header file.
extern const int g; // Declaration of g with external linkage
// could be placed into a header file
extern const int g = 3; // Definition of g with external linkage
// Not supposed to be in a header file
static int t; // Definition of t with internal linkage.
// may appear anywhere. Every translation unit that
// has a line like this has its very own t object.
你看,这相当复杂。有两个正交的概念:链接(外部与内部)和声明与定义的问题。 extern
关键字可以影响两者。关于链接,它与 static
相反。但是 static
的含义也被重载了——取决于上下文——控制或不控制链接。它做的另一件事是控制对象的生命周期(“静态生命周期”)。但是在全局范围内,所有变量都已经有一个静态的生命周期,有些人认为回收关键字来控制链接是个好主意(这只是我的猜测)。
链接基本上是在“命名空间范围”声明/定义的对象或函数的属性。如果它具有内部链接,则无法通过其他翻译单元的名称直接访问它。如果它有外部链接,则所有翻译单元只能有一个定义(异常(exception)情况,请参见 one-definition-rule)。
关于c++ - extern 关键字真的有必要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2840205/