C++ 同一文件中后跟extern的静态变量
下面的代码编译和执行都很好。C++ 同一文件中后跟extern的静态变量,c++,static,extern,C++,Static,Extern,下面的代码编译和执行都很好。 extern int a语句在static int a之后的确切含义是什么。 请注意,如果我在extern int a之后写入static int a,编译器会在测试时抛出错误。cpp:6:error:a声明为extern,随后声明为static #include<iostream> //#include "testh.h" using namespace std; static int a; extern int a; int main() {
extern int a
语句在static int a
之后的确切含义是什么。
请注意,如果我在extern int a
之后写入static int a
,编译器会在测试时抛出错误。cpp:6:error:a声明为extern,随后声明为static
#include<iostream>
//#include "testh.h"
using namespace std;
static int a;
extern int a;
int main()
{
int a;
a=3;
cout<<a<<endl;
cout<<::a<<endl;
return 0;
}
#包括
//#包括“testh.h”
使用名称空间std;
静态int a;
外部内部a;
int main()
{
INTA;
a=3;
cout您可以声明一个变量static
然后extern
,但不能声明extern
然后static
。结果是全局a
仍然具有内部链接。在语言标准文档的部分[dcl.stc]中有一个非常类似的示例(使用b
作为变量名)
,这说明了这一点。您可以声明一个变量静态
然后外部
,但不能声明外部
然后静态
。结果是全局a
仍然具有内部链接。有一个非常类似的示例(使用b
作为变量名)在语言标准文档的[dcl.stc]
部分中,说明了这一点。extern
不会导致编译器定义变量,而是声明现有的“某处”它。如果一个变量已经定义为static
,那么声明将被忽略。顺便说一句:您的主函数有另一个变量a
,它隐藏了名为a
的所有文件范围变量。我将static int a inside main称为::a
extern
不会导致编译器定义一个变量,而是反编译clares现有的“某处”它。如果一个变量已经被定义为static
,那么声明将被忽略。顺便说一句:您的主函数有另一个变量a
,它隐藏了名为a
的所有文件范围变量。我指的是main中的static int a作为::a