何时在 C 中使用 extern

新手上路,请多包涵

我正在阅读“Think in C++”,它刚刚介绍了 extern 声明。例如:

 extern int x;
extern float y;

我想我理解它的含义(没有定义的声明),但我想知道它什么时候证明有用。

有人可以提供一个例子吗?

原文由 Aslan986 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 350
2 个回答

当您有全局变量时,这很有用。您在头文件中声明全局变量的 _存在_,以便包含头文件的每个源文件都知道它,但您只需要在一个源文件中“定义”一次。

为了澄清,使用 extern int x; 告诉编译器类型为 int 的对象称为 x 存在 _于某处_。知道它存在于哪里不是编译器的工作,它只需要知道类型和名称,这样它就知道如何使用它。编译完所有源文件后,链接器会将 x 的所有引用解析为它在其中一个已编译源文件中找到的一个定义。为了让它工作, x 变量的定义需要有所谓的“外部链接”,这基本上意味着它需要在函数之外声明(通常称为“文件范围” ) 并且没有 static 关键字。

标题:

 #ifndef HEADER_H
#define HEADER_H

// any source file that includes this will be able to use "global_x"
extern int global_x;

void print_global_x();

#endif

来源1:

 #include "header.h"

// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;

int main()
{
    //set global_x here:
    global_x = 5;

    print_global_x();
}

来源 2:

 #include <iostream>
#include "header.h"

void print_global_x()
{
    //print global_x here:
    std::cout << global_x << std::endl;
}

原文由 dreamlax 发布,翻译遵循 CC BY-SA 4.0 许可协议

这都是关于 联动 的。

先前的答案对 extern 提供了很好的解释。

但我想补充一点。

你问的是 externC++ 中,而不是在 C 中,我不知道为什么没有答案提到当 extern const 时的情况。

在 C++ 中,一个 const 变量默认具有内部链接(不像 C)。

所以这种情况会导致 _链接错误_:

来源 1:

 const int global = 255; //wrong way to make a definition of global const variable in C++

来源 2:

 extern const int global; //declaration

它需要是这样的:

来源 1:

 extern const int global = 255; //a definition of global const variable in C++

来源 2:

 extern const int global; //declaration

原文由 Van Tr 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题