C++ static与extern

static 与 extern是用来做标识符作用域限定的。

程序1: test.cpp

#include <iostream>

using namespace std;

int MAX = 8 ;

void func1(){
	cout << "func1 output " << endl ;
}

其中定义了两个标识符, MAX和func1,由于他们都没有static修饰,他们默认的修饰符就是extern。

extern 说明这两个标识符在其它文件中也可以使用。

这里的其它文件是指没有 #include "test.cpp" 的文件,如果include了,就是同一个文件了

那其它文件怎么使用这两个标识符呢? 

程序2 : 

#include <iostream>
using namespace std;
extern int MAX ;
void func1() ;
int main()
{
	cout <<"Hello world!" << endl;
	cout << MAX << endl ;
	func1() ;

	return 0;
}

每一个要使用MAX而且没有包含"test.cpp"的文件,都需要用 extern int MAX  来声明这个变量,而函数的声明不需要extern修饰。

编译这两个文件  :

g++ main.cpp test.cpp

 

static 的作用是将标识符作用域限定在本文件内。

比如我们修改 test.cpp如下。

#include <iostream>

using namespace std;

static int MAX = 8 ;

void func1(){
	cout << "func1 output " << endl ;
}

修改main.cpp如下:

#include <iostream>
using namespace std;
void func1() ;
static int MAX = 100 ;
int main()
{
	cout <<"Hello world!" << endl;
	cout << MAX << endl ;
	func1() ;

	return 0;
}

将他们两个编译 : g++ main.cpp test.cpp 。 

如果把两个static都去掉,会报重复定义错误,去掉一个还可以。

 

简而言之:

extern的作用是不用include某个文件,也能通过extern声明使用这个文件中的全局变量。

static的作用是,如果两个文件不相互包含,而且分别都定义了相同名称的变量,为了让整体编译通过,要把它们其中一个定义为static。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值