理解 C++ 中的 Extern 关键字

Muhammad Husnain 2023年10月12日
  1. C++ 中的 extern 关键字
  2. C++ 中外部变量和外部函数的语法
  3. 在 C++ 中使用 extern 关键字的优点
理解 C++ 中的 Extern 关键字

本文将介绍 C++ 中的 extern 关键字、外部变量和函数的语法以及使用 this 关键字的用途。

C++ 中的 extern 关键字

关键字 extern 表示外部或全局变量和外部函数。该关键字告诉编译器该变量在许多源文件中是全局的。

extern 关键字在将多个源文件组合(链接)为单个程序时非常有用。

外部变量在头文件之后的主函数之外声明。外部变量的作用域是全局的,它的生命周期相当于静态变量(即生命周期等于程序的生命周期)。

C++ 中外部变量和外部函数的语法

可以使用以下语法声明外部变量和外部函数:

外部变量的语法:

extern datatype variable_name;
Example : extern int a = 40;

外部函数的语法:

extern datatype function_name();
Example : extern int add();

例子:

假设你有两个源文件:first.cppsecond.cpp,代码如下:

"first.cpp" Int a = 40;
Int b = 50;
Void add();
Int main() {
  add();
  return 0;
}
"Second.cpp" extern int a;
extern int b;
Void add() { a + b; }

在上面的例子中,变量 abfirst.cpp 中定义。然后要在 second.cpp 中使用这两个变量,都必须声明。

在 C++ 中使用 extern 关键字的优点

以下是在 C++ 程序中使用 extern 关键字的优点:

  • extern 关键字告诉编译器外部变量的存在以及它们在另一个翻译单元或源文件中的潜在用途。
  • 它增加了变量和函数的可见性。
  • 该关键字便于理解重复符号错误等错误。
  • 我们使用现代链接器的 extern 关键字来提高可读性。
  • 它使代码维护。
Muhammad Husnain avatar Muhammad Husnain avatar

Husnain is a professional Software Engineer and a researcher who loves to learn, build, write, and teach. Having worked various jobs in the IT industry, he especially enjoys finding ways to express complex ideas in simple ways through his content. In his free time, Husnain unwinds by thinking about tech fiction to solve problems around him.

LinkedIn

相关文章 - C++ Keyword