有关 extern const 的问题?

li_yirong 2002-02-05 11:26:47
在一个工程中的 file1.cpp 中定义 const int a=0;在另一个file2.cpp 中使用语句
"extern const int a; int i =a;" 结果编译出错,出错消息:unresolved external symbol "int const a".
而当我把 file1.cpp中的定义改为 extern const int a =0;编译通过.这是什么原因?
而在下面情况下编译是不会出错的:
//file1.cpp
int a=0;

//file2.cpp
extern int a;
int i =a;

这又是什么原因?
...全文
73 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wanghu 2002-02-06
  • 打赏
  • 举报
回复
const int a; a是编译时常量。
extern const int a; a不是编译时常量。
可用enum代替.
Linux2001 2002-02-06
  • 打赏
  • 举报
回复
的确,如果需要公用的东西最好放到头文件中
comanche 2002-02-06
  • 打赏
  • 举报
回复
习惯不好, 另一单元引用的常量要定义在 h 文件中
echolover 2002-02-06
  • 打赏
  • 举报
回复
在file1.cpp 中定义 const int a=0,编译器会将a看为一个编译期间的常量,不会为它分配内存的,在file2中自然就unresolved
pony12 2002-02-06
  • 打赏
  • 举报
回复
//file.h
const int ppp=999;
//file.cpp
extern const ppp;
int I=ppp; //OK

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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