c++ - extern 关键字真的有必要吗?

标签 c++ extern

...
#include "test1.h"

int main(..)
{
    count << aaa <<endl;
}

aaa定义在test1.h中,我没有使用extern关键字,但仍然可以引用aaa

所以我怀疑 extern 真的有必要吗?

最佳答案

extern 有其用途。但它主要涉及不受欢迎的“全局变量”。 extern 背后的主要思想是用外部链接来声明事物。因此,它有点与 static 相反。但在许多情况下,外部链接是默认链接,因此在这些情况下您不需要 externextern 的另一个用途是:它可以将定义变成声明。示例:

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/

相关文章:

c - 外部关键字和设置字符串变量

c++ - 使用 sigaltstack 动态更改运行信号处理程序的堆栈

c++ - 比 SetPixel() 更快的改变像素的方法

c++ - 复制 & copy_if 与 remove_copy & remove_copy_if

c - 将两个目标文件链接在一起会导致段错误 11

c++ - C++ 中的全局变量

c++ - 没有用于调用 std::vector<std::tuple> push_back 的匹配函数

c++ - std::vector::resize() 与 std::vector::reserve()

c - 翻译单元中 `static` 定义和 `extern declaration` 的顺序

c++ - 是否可以使用另一个 cpp 文件中定义的类而不是任何 header ?