1. 新建一个工程test2
2. 在工程中新建一个源文件(source file):file1.cpp,内容如下
#include <iostream>
using namespace std;
int main(){
int r;
double s;
cin>>r;
s=pi*r*r;
cout<<s<<endl;
return 0;
}
3. 在工程中新建一个源文件(source file):file2.cpp, 内容如下
double pi=3.14;
4. 由于全局变量pi=3.14是在file2.cpp中定义,file1.cpp看不到,所以编译会出错。
5. 修改file1.cpp, 使用extern声明语句声明外部变量pi,使得编译通过并执行。
file1.cpp
#include<iostream>
using namespace std;
int main()
{
int r;
double s;
cin>>r;
extern double pi; //使用extern声明语句声明外部变量pi
s=pi*r*r;
cout<<s<<endl;
return 0;
}
file2.cpp
double pi=3.14;