我们大概来谈一谈external 和 static 变量在使用的区别
1. 首先external变量是全局变量,你可以在头文件中申明某个变量是全局变量,external int a;但是不要赋值,如果你后面赋值就成为定义了。也就是不是声明,到其他地方在定义就是重复定义了。申明后, 你把这个头文件包含在其他的.cpp中间,你可以在任何一个cpp中间定义,但是不能定义两次。使用这个变量其实地址都是一个地址,不会改变。
但是如果在main函数中间又定义了一个int a;这并不会报错,它认为是一个函数体内的局部变量定义,他们重名了,但是编译器在这个局部定义后,值采用这个定以后的值,地址也不是原来那个地址了,但是那个外部全局变量还是存在的,你还是可以去引用的。当这个局部变量的作用域消失后,你还可以重新使用全局变量a.
2.static 在头文件static int a;其实就是声明和定义一起写了。不能在其它里面定义,如果包含了2次这样的头文件,那么就会重复定义。如果2个cpp包含这个头文件也只能有一个.cpp中间被定义了这个变量,另外的不需要在定义,也不能在定义。这两个.cpp中间的变量的地址是不一样的。
这是main.cpp
#include <stdio.h>
#include <iostream>
#include "1.h"
#include "2.h"
using namespace std;
int func()
{
return s;
}
int main()
{
repeatdef3();
repeatdef4();
for (int i=0; i<1; i++)
{
int s=4000;
cout<<"s: "<<s<<" "<<&s<<endl;
}
cout<<"s: "<<s<<" "<<&s<<endl;
repeatdef3();
repeatdef4();
cout<<"a: "<<a<<endl;
repeatdef();
repeatdef2();
//int s=90;
//printf("%d\n", a);
//printf("%d\n", b);
for (int i=0; i<2; i++)
{
for (int j=0; j<2; j++)
{
int k=0;
k += 1;
cout<<k<<endl;
}
// cout<<"a: "<<a<<endl;
}
printf("%d\n", s); //这里有问题
}
这是头文件
"1.h"
extern int s ; //static全局变量
void repeatdef3();
void repeatdef4();
"2.h"
#include <iostream>
void repeatdef();
void repeatdef2();
static int a=3;
//cout<<"a=: "<<endl;
"1.cpp"
#include "1.h"
#include <iostream>
int s=10;
void repeatdef3()
{
std::cout<<"s: "<<s<<" "<<&s<<std::endl;
}
"2.cpp"
#include "2.h"
void repeatdef()
{
std::cout<<"a: "<<&a<<std::endl;
}
"3.cpp"
#include "2.h"
#include "1.h"
#include <iostream>
void repeatdef4()
{
std::cout<<"s: "<<s<<" "<<&s<<std::endl;
}
void repeatdef2()
{
std::cout<<"a: "<<&a<<std::endl;
}