c++ extern的作用通俗来说的作用就是:
可以在一个文件中引用另一个文件中定义的变量或者函数
(1).先看引用同一个文件中的变量
#include <iostream>
using namespace std;
int main()
{
std::cout << a;
return 0;
}
int a = 100;
很明显上面的代码中我们不可能输出变量a的值,除非我们把int a =100放在最上面,但是我们不会那么做,我们是用extern来测试效果的,通过extern引用最下面的int a =100;
#include <iostream>
using namespace std;
int main()
{
extern int a;
std::cout << a;
return 0;
}
int a = 100;
(2).再看引用其他文件中的变量
创建main.cpp
#include <iostream>
using namespace std;
int main()
{
extern int a;
std::cout << a;
return 0;
}
创建other.cpp
#include <iostream>
using namespace std;
int a = 100;
int other()
{
std::cout << "this is other func";
return 0;
}
编译执行,正常运行。切记,引用其他文件中变量,这个变量在其他文件中必须是全局变量
(3).再看引用其他文件中的函数
创建main.cpp
#include <iostream>
using namespace std;
int main()
{
extern int other();
std::cout << other();
return 0;
}
创建other.cpp
int other()
{
return 110;
}
编译执行,正常运行。切记,引用其他文件中变量,这个变量在其他文件中必须是全局变量
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。