在未包含在任何其他文件中的文件中使用 extern 变量是否有任何可能的用途
Is there any possible use of using extern variable in a file that is not included in any other file?
我在网络上遇到过很多例子,这些例子在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
源文件中的未命名命名空间中。
相关文章:
- 在C++中使用没有合作伙伴Class/Cpp文件的头文件是否实用
- 在头文件上包含 cpp 文件是否有缺点?
- 如何检查文件是否已存在于 fstream C++中
- 预处理的 C/C++ 文件是否特定于计算机?
- 如何使用 jpeglib.h 获取文件是否为 JPEG 类型
- 如何在 Linux 下使用 c++ 知道文件是否被其他进程使用?
- 使用 g++ 编译时列出所有 cpp/cc 文件是否正常?
- 如何检查文件是否复制成功?(便携式解决方案)C++
- 如何检查 win32 exe 文件是否已运行?(使用 win32 API 代码)
- 如何检查每个头文件是否包含必需的包含文件?
- 为许多类可能需要的所有常量变量制作独立的头文件是否是一种很好的做法?
- 使用 CodeBlocks + GCC 构建的可执行文件是否可以在任何 Windows 上运行?
- 如何检查给定文件是否是C++中的有效视频文件?
- 关于使用ifstream在C 中确定文件是否存在的问题
- #include 包含的头文件已包含的头文件是否常见?
- 如何测试文件是否被锁定和/或只读而不打开?
- 检查文件是否具有Windows c ++的可执行权限
- 检查给定的多个文件是否存在
- .txt文件是否已关闭
- 如果给定正确的运行时库,x86 可执行文件是否可以在任何 x86 平台上运行