在未包含在任何其他文件中的文件中使用 extern 变量是否有任何可能的用途

Is there any possible use of using extern variable in a file that is not included in any other file?

本文关键字:文件 是否 任何可 变量 包含 任何 其他 extern      更新时间:2023-10-16

我在网络上遇到过很多例子,这些例子在main.c中extern int x,主要功能所在的位置。

据我所知,extern的唯一用途是在另一个文件中进行声明,并在定义后在另一个文件中使用它。

喜欢:A.H : extern int x;

空调 : int x = 5;

主.c : #include "a.h" // and start using x

第一种情况对我来说似乎是多余的。

所以在未包含在任何其他文件中的文件中使用extern变量是否有任何可能的用途?

extern告诉编译器x存在于不同的模块中,应该从其他地方链接。 直接将其放在main.c中只是避免拉入标头(无论如何都会包含在内联中)

就像在标头中一样,x仍然需要存在于另一个未定义extern的 .c 模块中

extern 变量基本上有两个函数,一个是使用另一个文件中的变量,另一个是访问全局变量,如下面的代码所示。

int x=10;
int main()
{
     int x=20;
     cout<<x;             //refers to x=20
     if(x==20)
     {
            extern int x;
            cout<<x;      //refers to the global x that is x=10
     }
 }

当然。在文件中使用 extern 允许您在该文件中使用该变量。它不必包含在其他任何地方。

使用 extern 会导致对象具有外部链接;使用对象(而不是值或类型)实例化模板,对象必须具有外部链接(至少在 C++03 中)。 大多数对象在命名空间作用域中定义具有全局链接,但 const 对象没有。所以你有这样的东西:

template <char const* n>
class Toto { /* ... */ };
char const n1[] = "abc";
Toto<n1> t1;    //  Illegal...
extern char const n2[] = "xyz";
Toto<n2> t2;    //  Legal...

这是一种特例,但它导致我(一两次)使用 extern源文件中的未命名命名空间中。