static 和 extern 问题

jeff_nie 2012-12-27 04:23:35
书上的例子,在两个文件中分别使用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

根据错误信息好像是重复定义了,请问是什么原因,谢谢。
...全文
110 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
jeff_nie 2012-12-27
  • 打赏
  • 举报
回复
引用 1 楼 turingo 的回复:
你的理解大体上是没有问题的,关键在于不要去#include "9.7.twofile2.cc",因为这样的话,两个文件相当于一个文件了,static和extern修饰已经没有意义,把#include "9.7.twofile2.cc"注释掉,然后类似这样编译即可: g++ file1.cc file2.cc
果然,多谢。
图灵狗 2012-12-27
  • 打赏
  • 举报
回复
你的理解大体上是没有问题的,关键在于不要去#include "9.7.twofile2.cc",因为这样的话,两个文件相当于一个文件了,static和extern修饰已经没有意义,把#include "9.7.twofile2.cc"注释掉,然后类似这样编译即可: g++ file1.cc file2.cc

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧