static 和 extern 问题
书上的例子,在两个文件中分别使用static和extern来定义变量,并打印它们。但我用g++ 无法编译代码如下:
file1
#include <iostream>
#include "9.7.twofile2.cc"
int tom = 3;
int dick = 30;
static int harry = 300;
void remote_access();
int main()
{
using namespace std;
cout << "main() reports the following addresses: \n";
cout << &tom << " = &tom, " << &dick << " = &dick, ";
cout << &harry << " = &harry\n";
remote_access();
return 0;
}
file2
#include <iostream>
extern int tom;
static int dick = 10;
int harry = 10;
void remote_access()
{
using namespace std;
cout << "remote_access() the following address: \n";
cout << &tom << " = &tom, " << &dick << " = &dick, ";
cout << &harry << " = &harry\n";
}
g++编译: g++ 9.6.twofile1.cc -o 9.6.twofile1
报错信息:
9.6.twofile1.cc:22: error: redefinition of ‘int dick’
9.7.twofile2.cc:20: error: ‘int dick’ previously defined here
9.6.twofile1.cc:23: error: redefinition of ‘int harry’
9.7.twofile2.cc:21: error: ‘int harry’ previously defined here
根据错误信息好像是重复定义了,请问是什么原因,谢谢。
[解决办法]
你的理解大体上是没有问题的,关键在于不要去#include "9.7.twofile2.cc",因为这样的话,两个文件相当于一个文件了,static和extern修饰已经没有意义,把#include "9.7.twofile2.cc"注释掉,然后类似这样编译即可:
g++ file1.cc file2.cc